<!-- 销售出库单 -->
<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-tooltip effect="dark" content="快捷键 Alt + N" :enterable="false" placement="bottom-start">
          <el-button :type="newBtnStatus ? 'primary' : ''" @click="onNewOrder">新单(N)</el-button>
        </el-tooltip>

        <el-tooltip effect="dark" content="快捷键 Alt + S" :enterable="false" placement="bottom-start">
          <el-button
            v-if="buttonsPermissions.LuRu"
            :disabled="saveBtnStatus"
            :class="saveBtnStatus ? 'disabled_button' : ''"
            :type="orderStatus == 66 ? 'primary' : ''"
            @click="onSubmit"
            >保存(S)</el-button
          >
          <el-button v-else class="disabled_button" disabled>保存(S)</el-button>
        </el-tooltip>

        <el-tooltip effect="dark" content="快捷键 Alt + A" :enterable="false" placement="bottom-start">
          <el-button
            v-if="buttonsPermissions.ShenHe"
            :disabled="auditBtnStatus"
            :class="auditBtnStatus ? 'disabled_button' : ''"
            :type="orderStatus == 0 ? 'primary' : ''"
            @click="onToExamine"
            :loading="examineLoading"
            >审核(A)</el-button
          >
          <el-button v-else class="disabled_button" disabled>审核(A)</el-button>
        </el-tooltip>
        <!-- 操作按钮 -->
        <el-select v-model="operationValue">
          <el-option
            @click.native="operationSelect(item.value)"
            v-for="item in operationData"
            :key="item.value"
            :label="item.value"
            :value="item.value"
            :disabled="item.disabled"
            v-if="!(item.value == '反审' && isBaseVersion)"
            :style="item.disabled ? 'pointer-events: none' : ''"
          ></el-option>
        </el-select>
        <!-- 调单 -->
        <el-select v-if="!isBaseVersion" v-model="exchangeValue" @change="exchangeSelect(exchangeValue)" :disabled="saveBtnStatus || isFromBill">
          <el-option v-for="item in exchangeOptions" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <!-- 导入导出 -->
        <!-- <el-button
          :disabled="!buttonsPermissions.DaoRu || (orderStatus != 66 && orderStatus != 0)"
          :class="(!buttonsPermissions.DaoRu || (orderStatus != 66 && orderStatus != 0)) ? 'disabled_button' : ''"
          @click="importExcel"
        >导入</el-button> -->
        <el-select v-model="importValue">
          <el-option
            v-if="buttonsPermissions.DaoRu"
            :disabled="orderStatus != 66 && orderStatus != 0"
            label="导入"
            value="导入"
            @click.native="importExcel"
            :style="orderStatus != 66 && orderStatus != 0 ? 'pointer-events: none' : ''"
          ></el-option>
          <el-option v-else disabled label="导入" value="导入" style="pointer-events: none"></el-option>
          <el-option
            v-if="buttonsPermissions.DaoChu"
            :disabled="orderStatus == 66"
            label="导出"
            value="导出"
            @click.native="exportExcel()"
            :style="orderStatus == 66 ? 'pointer-events: none' : ''"
          ></el-option>
          <el-option v-else disabled label="导出" value="导出" style="pointer-events: none"></el-option>
        </el-select>

        <el-tooltip effect="dark" content="快捷键 Alt + P" :enterable="false" placement="bottom-start">
          <el-button
            v-if="buttonsPermissions.DaYin"
            :disabled="orderStatus == 66"
            :class="orderStatus == 66 ? 'disabled_button' : ''"
            @click="handleShortcutKeyPrint()"
            >打印(P)</el-button
          >
          <el-button v-else class="disabled_button" disabled>打印(P)</el-button>
        </el-tooltip>

        <el-button @click="onShare" v-if="buttonsPermissions.FenXiang">分享</el-button>
        <el-button v-else class="disabled_button" disabled>分享</el-button>
        <el-button @click="onCheckBill">单据核对</el-button>
        <!-- 审核状态 -->
        <img v-if="orderStatus == 5" style="width: 50px; height: 38px; margin-right: 10px" src="@/assets/shenhe.png" />
        <img
          v-else-if="orderStatus == 10"
          style="width: 57px; height: 43px; margin-right: 10px"
          src="@/assets/zuofei.png"
        />
        <img
          v-else-if="orderStatus == 20"
          style="width: 57px; height: 24px; margin-right: 10px"
          src="@/assets/hongchong.png"
        />
        <span v-else style="color: #1993fb; margin-right: 10px">{{ queryData.orderStatus_dictText || '未保存' }}</span>
      </div>
      <div class="btn_right">
        <div style="display: flex; justify-content: space-between" ref="guide8">
          <el-tooltip effect="dark" content="上一条" :enterable="false" placement="top">
            <el-button @click="onUpper" class="arrow_btn" icon="el-icon-arrow-left" :loading="upperLoading" :disabled="isFromBill"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="下一条" :enterable="false" placement="top">
            <el-button
              style="margin-left: 0.1rem"
              @click="onLower"
              class="arrow_btn"
              icon="el-icon-arrow-right"
              :loading="lowerLoading"
              :disabled="isFromBill"
            ></el-button>
          </el-tooltip>
        </div>
        <div class="search_order">
          <span>单据编号：</span>
          <div class="order_number">{{ queryData.orderNumber }}</div>
        </div>
        <div class="bill_mask_back_view">
          <div v-if="maskViewStatus" class="bill_mask_view"></div>
          <el-checkbox :disabled="!supplementPermissions" v-model="queryData.isSupplement" @change="supplementChange"
            >补单</el-checkbox
          >
        </div>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_table">
        <div class="div_screen">
          <div class="custom_left bill_mask_back_view">
            <div v-if="maskViewStatus" class="bill_mask_view"></div>
            <!-- 供应商 -->
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 40px">客户</div>
                <span class="star">*</span>
              </div>
              <div class="custom_select_head">
                <el-tooltip
                  :disabled="xghCompany.length <= 6"
                  effect="dark"
                  :content="xghCompany"
                  :enterable="false"
                  placement="bottom-start"
                >
                  <el-select
                    :disabled="isFromBill"
                    v-model="queryData.xghCompanyId"
                    style="width: 100%"
                    filterable
                    ref="deptSelect"
                    @visible-change="(value) => handleFilterMethod('', 'companyName')"
                    :filter-method="(value) => handleFilterMethod(value, 'companyName')"
                  >
                    <el-option
                      v-for="item in gysOptions"
                      :key="item.id"
                      :label="item.companyName"
                      :value="item.id"
                      :disabled="item.status == '1'"
                    ></el-option>
                    <el-option v-if="companyAdd" key label value>
                      <div class="custom_add" @click.stop="onShowSupplierAdd">
                        <i class="el-icon-plus"></i>
                        <span>新增</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-tooltip>
                <div class="custom_more" v-if="!isFromBill">
                  <i class="el-icon-more" @click.stop="onShowSupplier"></i>
                </div>
                <!-- 编辑图标 -->
                <img v-if="!isFromBill" @click="onShowSupplierEdit" src="@/assets/img/edit_icon.png" style="width: 16px;height: 16px;cursor: pointer" />
              </div>
            </div>
            <!-- 出货仓库 -->
            <div class="custom_item">
              <div class="custom_star">
                <span class="custom_label" style="width: auto; min-width: 50px">出货仓库</span>
                <span class="star">*</span>
              </div>
              <div class="custom_select_head">
                <el-select
                  :disabled="isFromBill"
                  v-model="queryData.xghOutStorehouseId"
                  style="width: 100%; height: 30px"
                  @change="onChangeCk"
                  filterable
                  ref="deptSelect"
                  @visible-change="(value) => handleFilterMethod('', 'storehouseName')"
                  :filter-method="(value) => handleFilterMethod(value, 'storehouseName')"
                >
                  <el-option
                    v-for="item in ckOptions"
                    :key="item.id"
                    :label="item.storehouseName"
                    :value="item.id"
                  ></el-option>
                  <el-option v-if="storeAdd" key label value>
                    <div class="custom_add" @click.stop="onShowWhAdd">
                      <i class="el-icon-plus"></i>
                      <span>新增</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
            <!-- 经手人 -->
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 40px">经手人</div>
              </div>
              <div class="custom_select_head">
                <el-select
                  :disabled="isFromBill"
                  v-model="queryData.sysUserId"
                  style="width: 100%"
                  filterable
                  ref="deptSelect"
                  @visible-change="(value) => handleFilterMethod('', 'realname')"
                  :filter-method="(value) => handleFilterMethod(value, 'realname')"
                >
                  <el-option
                    v-for="item in jsrOptions"
                    :key="item.id"
                    :label="item.realname"
                    :value="item.id"
                  ></el-option>
                  <el-option key label value>
                    <div class="custom_add" @click.stop="onShowStaffAdd">
                      <i class="el-icon-plus"></i>
                      <span>新增</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
            <!-- 发票类型 -->
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 50px">发票类型</div>
              </div>
              <div class="custom_select_head">
                <el-select
                  :disabled="isFromBill"
                  v-model="queryData.invoiceType"
                  style="width: 100%"
                  filterable
                  ref="deptSelect"
                  @change="invoiceTypeChange"
                >
                  <el-option v-for="item in fpOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
                </el-select>
              </div>
            </div>
            <!-- 出库日期 -->
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 50px">出库日期</div>
              </div>
              <div class="custom_select_head">
                <el-date-picker
                  :disabled="(queryData.isSupplement && !isFromBill) ? false : true"
                  v-model="queryData.outTime"
                  value-format="yyyy-MM-dd"
                  style="height: 30px"
                ></el-date-picker>
              </div>
            </div>
            <!-- 收款日期 -->
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 50px">收款日期</div>
              </div>
              <div class="custom_select_head">
                <el-date-picker :disabled="isFromBill" v-model="queryData.collectionTime" value-format="yyyy-MM-dd"></el-date-picker>
              </div>
            </div>
          </div>
          <div class="screen_right">
            <i @click="onShowColumn()" class="set_up el-icon-s-tools"></i>
          </div>
        </div>
        <extendedFields ref="extendedFieldsRef" :disabled="maskViewStatus"></extendedFields>
        <div v-if="runningAccount" class="div_screen" style="justify-content: flex-start">
            <div class="custom_item">
              <div class="custom_star">
                <div class="custom_label" style="width: auto; min-width: 66px">单据明细：</div>
              </div>
              <div class="custom_select_head" style="display: flex; align-items: center">
                <div style="color: #fd6c21">应收款：{{ $formatMoney(billRecord.totalReceivable || 0) }}</div>
              </div>
            </div>
            <div class style="color: #fd6c21; margin-left: 50px; font-size: 12px">
              应收信用额：{{ $formatMoney(billRecord.receivableQuota || 0) }}
            </div>
        </div>
        <div class="table_content">
          <div>
            <NewTable
              ref="newTableRef"
              billName="销售出库"
              :TableConfig="TableConfig"
              :StorehouseList="ckOptions"
              :billDisabled="maskViewStatus"
              :companyId="queryData.xghCompanyId"
              :storehouseId="queryData.xghOutStorehouseId"
              :discountRate="queryData.orderRebate"
              :taxRate="taxRate"
              :isFromBill="isFromBill"
              orderName="salesBill"
              accessType="out"
              @onHandleSpData="onHandleSpData"
              @onHandleUnit="onHandleUnit"
              @onHandleAllPrice="onHandleAllPrice"
              @onHandleDrag="onDragColumn"
              @onUpdateColumn="onUpdateColumn"
            ></NewTable>
          </div>
        </div>
        <div class="table_calculation">
          <div style="flex-shrink: 0;">
            <div class="default" v-if="!showAttachment">
              <div class="default-button" @click="onShareResult()">客户确认信息</div>
              <span class="default-span" v-if="queryData.recordType">
                状态：<span :style="'color:'+getShareStateByCode(queryData.recordType.code).color">{{ queryData.recordType.text }}</span>
              </span>
            </div>
            <div class="calculation_div" v-if="showAttachment" style="padding-right: 10px;">
              <div class="table_item">
                <div class="switch_p">物流信息</div>
                <el-switch v-model="queryData.expressStatus" @change="expressStatusChange" :disabled="maskViewStatus"></el-switch>
                <div class="default">
                  <div class="default-button" @click="onShareResult()">客户确认信息</div>
                  <span class="default-span" v-if="queryData.recordType">
                    状态：<span :style="'color:'+getShareStateByCode(queryData.recordType.code).color">{{ queryData.recordType.text }}</span>
                  </span>
                </div>
              </div>
              <div v-if="queryData.expressStatus" class="bill_mask_back_view">
                <div v-if="maskViewStatus" class="bill_mask_view"></div>
              <div class="table_item ">
                <p>物流公司</p>
                <span>：</span>
                <el-select
                  style="width: 120px"
                  placeholder
                  v-model="queryData.xghExpressId"
                  filterable
                  @visible-change="(value) => handleFilterMethod('', 'expressName')"
                  :filter-method="(value) => handleFilterMethod(value, 'expressName')"
                >
                  <el-option
                    v-for="item in wlgsOptions"
                    :key="item.id"
                    :label="item.expressName"
                    :value="item.id"
                  ></el-option>
                  <el-option key label value v-if="expressAdd">
                    <div class="custom_add" @click.stop="onShowLogisticsAdd">
                      <i class="el-icon-plus"></i>
                      <span>新增</span>
                    </div>
                  </el-option>
                </el-select>
                <p style="margin-left: 10px; width: 35px">单号</p>
                <span>：</span>
                <el-input style="width: 150px" v-model="queryData.expressNumber"></el-input>
              </div>
              <div class="table_item">
                <p>物流运费</p>
                <span>：</span>
                <p class="payDate_input width_sty" style="width: 120px">
                  <el-input v-model="queryData.expressPrice" @blur="expressProceBlur" @focus="focusSelect"></el-input>
                  <i @click="onShowDialogPaymentWl" class="el-icon-more"></i>
                </p>
                <p style="margin-left: 10px; width: 35px">已付</p>
                <span>：</span>
                <el-checkbox v-model="queryData.expressPayStatus" @change="expressPayStatusChange"></el-checkbox>
              </div>
              <div class="table_item">
                <p>物流代收</p>
                <span>：</span>
                <el-input
                  style="width: 120px"
                  v-model="queryData.expressPayPrice"
                  @blur="onSureExpressPrice"
                  @focus="focusSelect"
                ></el-input>
                <div class="question_mark" @click="showWlTips = !showWlTips" style="margin-left: 10px">
                  <svg-icon icon-class="questionMark"></svg-icon>
                </div>
                <div v-if="showWlTips" @click="showWlTips = !showWlTips" class="tips_div">
                  <div style="align-items: center; display: flex">
                    <svg-icon class="exclamatory_mark" icon-class="exclamatoryMark" :size="16"></svg-icon>
                    <span>物流公司付给你的钱。</span>
                  </div>
                  <i class="el-icon-close"></i>
                </div>
              </div>
            </div>
            </div>
          </div>
          <div>
            <div>
              <div class="default-button" style="min-width: 85px;margin: 0;" @click="applyCode" v-if="paymentCode.length < 1">生成收款码</div>
              <div v-else>
                <div
                style="position: relative;margin: 0;width: 65px;height: 65px;"
                class="attachment_view"
                v-for="(item, index) in paymentCode"
                :key="index"
              >
                <el-image
                  style="width: 100%; height: 100%; border-radius: 3px"
                  :src="item"
                  :preview-src-list="paymentCode"
                >
                </el-image>
                <!-- <div class="attachment_mask">
                  <img src="@/assets/att_del.png" style="width: 100%;height: 100%" @click="delPaymentCode(index)" />
                </div> -->
                <div class="attachment_mask_pre">
                  <img src="@/assets/att_pre.png" />
                </div>
              </div>
              </div>
            </div>
            <div class="act_view" v-if="showAttachment">
              <div style="margin-bottom: 3px;">附件信息：</div>
              <div style="display: flex; flex-wrap: wrap">
                <div
                  style="position: relative"
                  class="attachment_view"
                  v-for="(item, index) in attachments"
                  :key="index"
                >
                  <el-image
                    style="width: 100%; height: 100%; border-radius: 3px"
                    :src="item"
                    :preview-src-list="attachments"
                  >
                  </el-image>
                  <div class="attachment_mask" v-if="!maskViewStatus">
                    <img src="@/assets/att_del.png" style="width: 100%;height: 100%" @click="delAttachment(index)" />
                  </div>
                  <div class="attachment_mask_pre">
                    <img src="@/assets/att_pre.png" />
                  </div>
                </div>
                <el-upload
                  v-if="attachments.length < 5 && !maskViewStatus"
                  class="uploader"
                  :action="uploadAction"
                  :on-success="handleSuccess"
                  :headers="headers"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  list-type="picture"
                  multiple
                >
                  <img src="@/assets/att_add.png" style="width: 100%; height: 100%" />
                </el-upload>
                <div v-else-if="attachments.length < 5" class="uploader" style="cursor: no-drop;">
                  <img src="@/assets/att_add.png" style="width: 100%; height: 100%" />
                </div>
              </div>
              <div style="font-size: 9px;">支持扩展名：.jpg .jpeg .png 最多上传5张</div>
            </div>
            <div class="calculation_div bill_mask_back_view" style="margin-left: 20px">
              <div v-if="maskViewStatus" class="bill_mask_view_script"></div>
              <div class="table_item">
                <p>整单折扣</p>
                <span>：</span>
                <el-input
                  style="width: 120px"
                  v-model="queryData.orderRebate"
                  @change="onChangeDiscount"
                  :max="100"
                  :min="1"
                  type="number"
                ></el-input>
                <p style="margin-left: 10px">整单优惠</p>
                <span>：</span>
                <el-input
                  style="width: 120px"
                  v-model="queryData.orderDiscountPrice"
                  onkeyup="value=value.replace(/[^\d.]/g,'')"
                  @blur="onChangeOrderDiscountPrice()"
                  @focus="focusinSelect"
                ></el-input>
              </div>
              <div class="table_item">
                <p>收款账户</p>
                <span>：</span>
                <p class="payDate_input" style="width: 120px">
                  <el-input v-model="queryData.bankName"></el-input>
                  <i @click="onShowDialogPaymentZh" class="el-icon-more"></i>
                </p>
                <p style="margin-left: 10px">本次收款</p>
                <span>：</span>
                <el-input
                  style="width: 120px"
                  v-model="queryData.collectionPrice"
                  onkeyup="value=value.replace(/[^\d.]/g,'')"
                  @blur="onChangepayPrice(queryData.collectionPrice)"
                  @focus="focusinSelect"
                ></el-input>
              </div>
              <div class="table_item">
                <p>备注</p>
                <span>：</span>
                <el-input v-model="queryData.remark" v-if="!maskViewStatus || !queryData.remark"></el-input>
                <el-tooltip v-else :content="queryData.remark" placement="top">
                  <el-input v-model="queryData.remark" :disabled="maskViewStatus" style="z-index: 11"></el-input>
                </el-tooltip>
              </div>
              <div class="table_item">
                <p>附记</p>
                <span>：</span>
                <el-input v-model="queryData.postscript" @blur="updatePostScript()"></el-input>
              </div>
            </div>
            <div class="calculation_div" style="margin-left: 20px">
              <div class="table_item">
                <p>应收金额</p>
                <span>：</span>
                <span class="span_style">¥{{ formatReceivablePrice }}</span>
              </div>
              <div class="table_item">
                <p>本次欠款</p>
                <span>：</span>
                <span>¥{{ formatOwePrice }}</span>
              </div>
              <div class="table_item">
                <p>制单人</p>
                <span>：</span>
                <span>{{ queryData.createName ? queryData.createName : $lcStorage.get('xghUser').realname }}</span>
                <el-button plain @click="onShowLog" style="margin-left: 10px">操作日志</el-button>
              </div>
              <div class="table_item">
                <p>制单日期</p>
                <span>：</span>
                <span>{{ formatCreateOrderDate }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 列配置弹框 -->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="getColumnList"
      :defaultColumnDataArr="defaultColumnData"
      :orderType="pageName"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    <!-- 选择客户弹框 -->
    <DialogSupplier ref="supplierRef" @onSelectSupplier="onSelectSupplier"></DialogSupplier>
    <!-- 新增客户弹框 -->
    <DialogSupplierAdd
      ref="supplierAddRef"
      :newData="newData"
      @dialogVisibleClose="onCloseAddSupplier"
      @onAddSubmit="onAddSupplier"
    ></DialogSupplierAdd>
    <!-- 选择账户支付弹框 -->
    <DialogPayment
      ref="paymentRef"
      :paymentData="paymentData"
      :titleName="paymentTitleName"
      @onSelectPayment="onSelectPayment"
    ></DialogPayment>
    <!-- 新增仓库弹框 -->
    <DialogWarehouseAdd
      ref="warehouseAddRef"
      :newData="newWhData"
      @onAddSubmit="onAddWh"
      @handleClose="onCloseAddWh"
    ></DialogWarehouseAdd>
    <!-- 新增物流公司 -->
    <DialogDLogisticsAdd ref="dialogLogisticsAdd" @onAddSubmit="onAddLogistics"></DialogDLogisticsAdd>
    <!-- 新增员工弹框 -->
    <DialogStaffAdd ref="staffAddRef" @dialogVisibleClose="onCloseAddStaff" @onAddSubmit="onAddStaff"></DialogStaffAdd>
    <!-- 提醒弹框 -->
    <PopupReminder ref="reminderRef" :tipsData="tipsData" @onConfirm="onYes" @onCancel="onCancel"></PopupReminder>
    <!-- 成功弹框 -->
    <PopupSuccess ref="successRef" :tipsData="tipsData" @onConfirm="onOptionSuccess"></PopupSuccess>
    <!-- 操作日志 -->
    <DialogOperationLog :logTitle="logTitle" ref="operationLogRef"></DialogOperationLog>
    <!-- 反审支付弹框 -->
    <PopupDeApproval ref="deApprovalRef" @onConfirmFree="onUnToExamine"></PopupDeApproval>
    <!-- 导入 -->
    <DialogImport
      ref="daoru"
      :titles="TableConfig.columnData"
      :storehouseId="queryData.xghOutStorehouseId"
      url="/xghSaleStorehouseOrder/xghSaleStorehouseOrder/importExcel"
      @importData="importData"
      @downloadTemplate="exportExcel"
    ></DialogImport>
    <!-- 单价为零时的弹窗 -->
    <DialogPriceZero
      :showPriceZeroDialog="showPriceZeroDialog"
      :priceZeroGoodsData="priceZeroGoodsData"
      @priceZeroCallback="priceZeroCallback"
    ></DialogPriceZero>
    <!-- 销售价低于成本价时的弹窗 -->
    <DialogPriceBelow
      :showPriceZeroDialog="showPriceBelowDialog"
      :priceZeroGoodsData="priceBelowGoodsData"
      @priceZeroCallback="priceBelowCallback"
    ></DialogPriceBelow>
    <!-- 负库存的弹窗 -->
    <DialogNegativeInventory
      :showPriceZeroDialog="showNegativeInventoryDialog"
      :priceZeroGoodsData="negativeInventoryData"
      @priceZeroCallback="negativeInventoryCallBack"
    ></DialogNegativeInventory>
    <!-- 单据状态变更提示 -->
    <dialogSimplePrompt ref="simplePrompt" @onSure="hongchongSure"></dialogSimplePrompt>
    <!-- 单据核对 -->
    <dialogBillContrast ref="billContrast"></dialogBillContrast>
    <!-- 调单 -->
    <dialogTransferBill ref="transferBill" @onSelectBill="transferBillCallback"></dialogTransferBill>
    <!-- 打印 -->
    <dialog-print ref="print"></dialog-print>
    <dialog-share ref="share"></dialog-share>
    <!-- 申请收款码/小程序码弹窗 -->
    <dialog-apply ref="applyCode"></dialog-apply>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import dialogSimplePrompt from '../../components/dialogSimplePrompt' //单据操作提示
import dialogBillContrast from '../../components/dialogBillContrast' //单据核对
import dialogTransferBill from '../../components/dialogTransferBill' //调单
import DialogDLogisticsAdd from '@/views/components/dialogLogisticsAdd'
import CConfiguration from '@/components/c_column/columnConfiguration1'
import DialogSupplier from '../../components/dialogSupplier'
import DialogSupplierAdd from '../../components/dialogSupplierAdd'
import DialogPayment from '../../components/dialogPayment'
import PopupReminder from '../../components/popupReminder'
import PopupSuccess from '../../components/popupSuccess'
import DialogOperationLog from '../../components/dialogOperationLog'
import PopupDeApproval from '../../components/popupDeApproval'
import { ACCESS_TOKEN, TENANT_ID, USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import Vue from 'vue'
/*商品列表 */
import NewTable from '@/components/c_table/newTable'
/*新增仓库 */
import DialogWarehouseAdd from '../../components/dialogWarehouseAdd'
/*新增经手人 */
import DialogStaffAdd from '../../components/dialogStaffAdd'
/*导入弹窗 */
import DialogImport from '@/components/c_Import/index1'
/**单价为0时的弹窗 */
import DialogPriceZero from '../../components/dialogPriceZero'
/**销售价低于成本价时的弹窗 */
import DialogPriceBelow from '../../components/dialogPriceBelow'
/**负库存的弹窗 */
import DialogNegativeInventory from '../../components/dialogNegativeInventory'
/**打印 */
import dialogPrint from '../../components/dialogPrint.vue'
import dialogShare from '../../components/dialogShare.vue'
import dialogApply from '../../components/dialogApply.vue'
import { getAction, postAction, downPostFile, putAction } from '@/api/manage'

import extendedFields from '../../components/extendedFields/extendedFields.vue'

// 导入调用处理权限数据方法
import {
  handlePermissions,
  handleOtherPerms,
  sysConfig,
  getSystemParamsByName,
  formatFour,
  formatMoney,
  formatPrice,
  formatNumber,
  delcommafy,
  handleArrayToObject,
  handleObjectToArray,
  formatHundredMillionPrice,
  getPrintCompanyInfo,
  getCompanyList,
  accMul,
  accAdd,
  accSub,
  getAttributeOrderInfoRequest,
  handleIsBaseVersion
} from '@/utils/index'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { format } from 'echarts'
export default {
  name: 'billSalesDelivery',
  mixins: [JeecgListMixin],
  components: {
    CConfiguration,
    DialogSupplier,
    DialogSupplierAdd,
    DialogPayment,
    PopupReminder,
    PopupSuccess,
    DialogOperationLog,
    PopupDeApproval,
    NewTable,
    DialogWarehouseAdd,
    DialogStaffAdd,
    DialogImport,
    DialogPriceZero,
    dialogSimplePrompt,
    dialogBillContrast,
    dialogTransferBill,
    DialogPriceBelow,
    DialogNegativeInventory,
    DialogDLogisticsAdd,
    dialogPrint,
    extendedFields,
    dialogShare,
    dialogApply
  },
  computed: {
    ...mapGetters(['isSupplementOrder']),
    //orderStatus 订单状态：新单66、0待审核、5审核通过、10作废、15反审、20红冲、25终止、30完成
    newBtnStatus() {
      return this.orderStatus == 5 || this.orderStatus == 10 || this.orderStatus == 20 || this.orderStatus == 30
    },
    saveBtnStatus() {
      return this.orderStatus == 5 || this.orderStatus == 10 || this.orderStatus == 20 || this.orderStatus == 30
    },
    auditBtnStatus() {
      return (
        this.orderStatus == 66 ||
        this.orderStatus == 5 ||
        this.orderStatus == 10 ||
        this.orderStatus == 20 ||
        this.orderStatus == 25 ||
        this.orderStatus == 30
      )
    },
    maskViewStatus() {
      return this.orderStatus != 66 && this.orderStatus != 0
    },
    getColumnList() {
      return handleObjectToArray(this.TableConfig.columnData)
    },
    formatReceivablePrice() {
      return formatHundredMillionPrice(this.queryData.receivablePrice)
    },
    formatOwePrice() {
      return formatHundredMillionPrice(this.queryData.owePrice)
    },
    formatCreateOrderDate() {
      let date = this.queryData.createOrderDate
      if (date.length > 10) {
        date = date.slice(0, 10)
      }
      return date
    },
    expressAdd() {
      return handlePermissions('物流信息').XinZeng
    },
    storeAdd() {
      return handlePermissions('仓库信息').LuRu
    },
    buttonsPermissions() {
      return handlePermissions('销售出库')
    },
    companyAdd() {
      return handlePermissions('往来单位').LuRu
    },
    supplementPermissions() {
      return handleOtherPerms('补录单据')
    },
    printPermissions() {
      return handleOtherPerms('单据可多次打印')
    },
    /**销售价格低于成本价预警 */
    isBelowCost() {
      return sysConfig().sell_below_cost_alarm
    },
    /**单据保存后立即开新单 */
    isSaveNewOrder() {
      return sysConfig().open_new_order_after_document_saved
    },
    /**单据保存后立即审核 */
    isSaveExamine() {
      return sysConfig().verify_order_after_document_saved
    },
    /**单据审核后立即开新单 */
    isExamineNewOrder() {
      return sysConfig().open_new_order_after_document_verify
    },
    // 2、启用价格跟踪
    PriceTracking() {
      return sysConfig().enable_price_tracking
    },
    // 3、启用折扣率跟踪
    discountTracking() {
      return sysConfig().enable_discount_tracking
    },
    // 保存时单价为0不提示
    isInputSkip() {
      return sysConfig().unit_price_zero_no_prompt
    },
    // 显示往来账
    runningAccount() {
      return sysConfig().option_company_running_account
    },
    showAttachment() {
      let route = this.$route
      let av = Vue.ls.get('accountVersion')
      return av && av != '专业版' && av != '必用版'
    },
    isBaseVersion() {
      return handleIsBaseVersion()
    }
  },
  created() {
    console.log(' 销售出库单 created ')

    let accountBook = Vue.ls.get(ACCOUNT_BOOK)
    this.accountBookId = accountBook && accountBook.id
    this.getData()

    if (!this.$route.params.billId) {
      //开新单
      this.onNewOrder()
    }
    if(this.$route.params.xghCompanyId){
      this.queryData.xghCompanyId = this.$route.params.xghCompanyId
    }
  },
  watch: {
        'queryData.xghCompanyId': {
            deep: true,
            handler() {
                this.getBillRecord();
                this.totalCompanys.forEach((item) => {
                    if (item.id == this.queryData.xghCompanyId) {
                        this.xghCompany = item.companyName;
                    }
                });
            },
        },
        orderStatus() {
            this.handleOperationData();
        },
        $route: {
          immediate: true,
          handler() {
              if (this.$route.name === 'saleManage-salesBill-billSalesDelivery') {
                  let bId = this.$route.params.billId;
                  if (bId && bId != this.billIdsList) { // 使用billIdsList进行判断
                      this.billIdsList = bId; // 更新billIdsList
                      this.billId = bId
                      if (bId.includes('|')) {
                          this.isFromBill = true;
                          this.billId = '';
                          const [pageSource, encodedBillId] = bId.split('|', 2);
                          const billIdArray = JSON.parse(encodedBillId);

                          // 公共初始化逻辑
                          const initializeState = () => {
                              this.orderStatus = 66;
                              this.TableConfig.tableData = [];
                              this.queryData = { ...this.$options.data().queryData };
                              this.queryData.outTime = this.$formatDateTime();
                              this.queryData.createOrderDate = this.$formatDateTime();
                              this.queryData.createName = this.$lcStorage.get('xghUser').realname;
                              this.attachments = [];
                              this.paymentEcho = {};
                              this.xghExpressDetail = {};
                              this.collectionPayPage = {};
                          };
                          // 公共数据处理逻辑
                          const processData = (res, idMapper) => {
                              if (res.code === 200) {
                                  const dataList = {
                                      billName: '销售订单',
                                      goodsList: res.result.map(item => ({
                                          ...item,
                                          id: '', // 强制清空 ID
                                          goodsId: item.goodsId,
                                          goodsName: item.goodsName,
                                          unit: item.unit,
                                          number: item.notDeliverNumber,
                                          salePrice: item.salePrice,
                                          xghStorehouseId: item.xghStorehouseId,
                                          discountRate: item.discountRate || 100,
                                          discountUnitPrice: item.discountUnitPrice,
                                          taxRate: item.taxRate,
                                          allPrice: item.allPrice,
                                          deliverNum: item.deliverNumber,
                                          isGive: item.isGift !== '1', // 简化布尔值转换
                                          goodsManyNorms: item.goodsManyNorms,
                                          callDocumentId: item.id,
                                          callDocumentType: 5,
                                          goodsCode: item.goodsCode,
                                          norms: item.norms
                                      })),
                                      billObj: {
                                          ...billIdArray[0].billObj,
                                          invoiceType: billIdArray[0].invoiceType || '0',
                                          remark: billIdArray[0].remark || '',
                                      }
                                  };
                                  this.TableConfig.tableData = [];
                                  this.transferBillCallback(dataList);
                              } else {
                                  this.$elMessage.error(res.message);
                              }
                          };

                          // API请求封装
                          const fetchOrderData = (apiPath, idMapper) => {
                              getAction(apiPath, {
                                  ids: billIdArray.map(idMapper).join(',')
                              }).then(res => processData(res, idMapper));
                          };

                          this.$nextTick(() => {
                              initializeState();

                              const apiConfig = {
                                  'salesOrderDetailsQuery': {
                                      path: '/xghSaleOrder/xghSaleOrder/querySaleOrderDetailByIds',
                                      idMapper: item => item.saleOrderInfoId
                                  },
                                  'salesOrderExecution': {
                                      path: '/xghSaleOrder/xghSaleOrder/querySaleOrderDetailByOrderIds',
                                      idMapper: item => item.id
                                  }
                              };

                              if (apiConfig[pageSource]) {
                                  const { path, idMapper } = apiConfig[pageSource];
                                  fetchOrderData(path, idMapper);
                              } else {
                                  this.isFromBill = false;
                                  this.getOrderDetailById();
                              }
                          });
                      } else {
                          this.isFromBill = false;
                          this.getOrderDetailById();
                      }
                  }
              }
          },
      },
  },
  data() {
    return {
      shareOptions: [
        { value: '2', label: '已签字', color: '#0089FF' },
        { value: '7', label: '已分享', color: '#FD6C21' },
        { value: '0', label: '未分享', color: '#666666' },
      ],
      billIdsList: '',
      isFromBill: false,
      billId: '',
      pageName: '销售出库单',
      accountBookId: '',
      // 存储按钮权限数据
      // buttonsPermissions: {},
      // supplementPermissions: false,
      // printPermissions: false,
      // storeAdd: false, // 仓库新增权限
      // companyAdd: false, // 往来单位权限
      // 传递给弹框的数据
      tipsData: {
        tipsWords: '',
        tipsMark: '',
        resultType: -1, //1、保存或编辑成功 2、审核成功
      },
      /**操作日志 */
      logTitle: '',
      paymentTitleName: '', //支付弹框名称
      paymentType: '', //支付弹窗类型 1：物流 2：收款
      showWlTips: false,
      operationValue: '操作',
      operationData: [],
      exchangeValue: '调单',
      exchangeOptions: ['调用销售订单', '调用采购入库单', '调用调拨单'],
      importValue: '导入',
      importOptions: [
        {
          value: '导入',
          label: '导入',
        },
        {
          value: '导出',
          label: '导出',
        },
      ],
      // 供应商
      gysOptions: [],
      // 物流公司
      wlgsOptions: [],
      // 出货仓库
      ckOptions: [],
      // 新增仓库数据
      newWhData: {},
      paymentData: [],
      // 付款多账户数据
      paymentEcho: {
        xghCollectionPayInfoList: [],
      },
      // 物流运费多账户数据
      expressPaymentEcho: [],
      // 经手人
      jsrOptions: [],
      // 发票类型
      fpOptions: [],
      // 税率
      taxRate: 0,
      // 单位
      dwOptions: [],
      extendFields:[],
      // 查询条件数据
      xghCompany: '', //客户
      queryData: {
        id: '',
        orderState: '', //订单状态 0.待审核5.审核通过10.作废15.反审20.红冲25.终止30.完成
        orderNumber: '', // 单据编号
        xghCompanyId: '', //客户id
        xghOutStorehouseId: '', //出货仓库id
        sysUserId: '', //经手人id
        invoiceType: '0', // 发票类型
        outTime: '', //订单日期
        orderStatus: '0', //订单状态 0.待审核5.审核通过10.作废15.反审20.红冲25.终止30.完成
        orderType: 6, ////采购订单1/采购入库单2/采购退货单3/采购换货单4/销售订单5/销售出库单6/销售退货单7/销售换货单8/盘点单9/报损单10
        isSupplement: false, //是否补单
        orderRebate: '100', //整单折扣率
        orderDiscountPrice: 0, //整单优惠金额
        bankName: '', // 收款账户
        bankId: '', // 账户id
        collectionPrice: 0, //预付定金
        remark: '', //备注
        postscript: '', //附记
        allPrice: formatMoney(0), // 整单优惠前总金额
        receivablePrice: formatMoney(0), //应收款
        orderAllPrice: formatMoney(0), //订单总金额 订单总金额=整单折扣金额+优惠金额+预付定金+实付金额
        owePrice: formatMoney(0), //本次欠款金额
        createName: '', //制单人
        createOrderDate: '', //制单日期（当前日期）
        collectionTime: '', //付款日期

        /**物流信息 */
        expressStatus: false,
        xghExpressId: '', //物流公司id
        expressNumber: '', //物流单号
        xghExpressDetailId: '', //物流代收信息id
        expressPayStatus: false, //物流状态 1.运费已付 0.未付
        expressPayPrice: '0.00', //物流代付金额
        expressPrice: '0', //运费
        attachment: '',
      },
      xghExpressDetail: {}, //物流运费信息
      collectionPayPage: {}, //应收应付信息
      shareOrderNumber: '', //分享订单编号
      // 表格数据
      tableData: [],

      // 列配置数据
      defaultColumnData: [],
      TableConfig: {
        // 表头数据
        columnData: {
          idx: {
            isShow: true,
            cellWidth: '80px',
            morenName: '序号',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            noModify: true,
            props: 'idx',
          },
          goodsNumber: {
            isShow: true, //是否显示当前列
            showLength: true,
            cellWidth: '150px',
            morenName: '商品编码',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            noModify: true,
            props: 'goodsNumber',
          },
          goodsCode: {
            isShow: true,
            cellWidth: '150px',
            morenName: '条形码',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            noModify: false,
            props: 'goodsCode',
          },
          goodsName: {
            isShow: true,
            isRequired: true,
            showType: 'table',
            cellWidth: '150px',
            morenName: '商品名称',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            noModify: true,
            props: 'goodsName',
          },
          norms: {
            isShow: true,
            cellWidth: '100px',
            morenName: '规格',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'norms',
          },
          unit: {
            isShow: true,
            showType: 'selectDw',
            cellWidth: '100px',
            morenName: '单位',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'unit',
          },
          unitList: {
            isShow: false,
            morenName: '单位数据',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'unitList',
          },
          xghStorehouseId: {
            isShow: true,
            isRequired: true,
            showType: 'selectCk',
            cellWidth: '120px',
            morenName: '出货仓库',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'xghStorehouseId',
          },
          numberShow: {
            isShow: true,
            isRequired: true,
            showType: 'input',
            isSum: true,
            sumValue: 0,
            cellWidth: '100px',
            morenName: '数量',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'numberShow',
          },
          salePriceShow: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '销售单价',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'salePriceShow',
          },
          discountRate: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '折扣率%',
            zidingyiName: '',
            morenState: true,
            zidingyiState: false,
            props: 'discountRate',
          },
          discountUnitPriceShow: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '折扣单价',
            zidingyiName: '',
            morenState: true,
            zidingyiState: false,
            props: 'discountUnitPriceShow',
          },
          taxRate: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '税率%',
            zidingyiName: '',
            morenState: true,
            zidingyiState: false,
            props: 'taxRate',
          },
          taxUnitPriceShow: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '含税单价',
            zidingyiName: '',
            morenState: true,
            zidingyiState: false,
            props: 'taxUnitPriceShow',
          },
          taxPriceShow: {
            isShow: true,
            cellWidth: '100px',
            morenName: '税额',
            zidingyiName: '',
            morenState: true,
            zidingyiState: false,
            props: 'taxPriceShow',
          },
          allPriceShow: {
            isShow: true,
            showType: 'input',
            isSum: true,
            sumValue: 0,
            cellWidth: '100px',
            morenName: '金额',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'allPriceShow',
          },
          deliverNum: {
            isShow: true,
            showType: 'input',
            isSum: true,
            sumValue: 0,
            cellWidth: '100px',
            morenName: '送货数量',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'deliverNum',
          },
          isGive: {
            isShow: true,
            showType: 'check',
            cellWidth: '60px',
            morenName: '赠品',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'isGive',
          },
          remark: {
            isShow: true,
            showType: 'input',
            cellWidth: '100px',
            morenName: '备注',
            zidingyiName: '',
            morenState: true,
            zidingyiState: true,
            props: 'remark',
          },
          extendField1: {
            isShow: true,
            showType: 'input',
            noCustom: true,
            morenName: '商品扩展属性一',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendField1',
          },
          extendField2: {
            isShow: true,
            showType: 'input',
            noCustom: true,
            morenName: '商品扩展属性二',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendField2',
          },
          extendField3: {
            isShow: true,
            showType: 'input',
            noCustom: true,
            morenName: '商品扩展属性三',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendField3',
          },
          extendField4: {
            isShow: true,
            showType: 'input',
            noCustom: true,
            morenName: '商品扩展属性四',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendField4',
          },
          extendField5: {
            isShow: true,
            showType: 'input',
            noCustom: true,
            morenName: '商品扩展属性五',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendField5',
          },
          extendValue1: {
            isShow: true,
            editHeader: false,
            morenName: '明细扩展数值一',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendValue1',
          },
          extendValue2: {
            isShow: true,
            editHeader: false,
            morenName: '明细扩展数值二',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendValue2',
          },
          extendValue3: {
            isShow: true,
            editHeader: false,
            morenName: '明细扩展数值三',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendValue3',
          },
          extendValue4: {
            isShow: true,
            editHeader: false,
            morenName: '明细扩展数值四',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendValue4',
          },
          extendValue5: {
            isShow: true,
            editHeader: false,
            morenName: '明细扩展数值五',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'extendValue5',
          },
          formulaId: {
            isShow: true,
            morenName: '计算公式名称',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'formulaId',
          },
          formula: {
            isShow: true,
            morenName: '自定义计算公式',
            zidingyiName: '',
            morenState: false,
            zidingyiState: false,
            cellWidth: '180px',
            noModify: false,
            props: 'formula',
          }
        },
        // 表格数据
        tableData: [],
      },
      orderId: '', // 单据id
      orderFlag: 0, //先点上一单传1，先点下一单传2，点新单重置
      orderStatus: 0, // 当前单据的状态 66表示新单
      updateId: '', // 修改列配置时返回的id
      showLiepeizhi: false, //是否显示列配置
      scanCode: '',
      /**定义单据信息对象 */
      // 传递给操作日志的值
      logData: {
        orderId: -1,
        orderType: '销售出库单',
      },
      examineLoading: false,
      isCreditLimit: false,
      showPriceZeroDialog: false,
      priceZeroGoodsData: {}, //价格为零的商品
      showPriceBelowDialog: false,
      priceBelowGoodsData: {}, //销售价低于成本价的商品
      negativeInventory: false,
      showNegativeInventoryDialog: false,
      negativeInventoryData: {}, //负库存的商品
      pageNo: 0, //
      pageTotal: 1,
      lowerLoading: false,
      upperLoading: false,
      url: {
        api: '销售出库单列配置',
        exportXlsUrl: '/xghSaleStorehouseOrder/xghSaleStorehouseOrder/exportDetailXls',
      },
      printData: {},
      billRecord: {},

      saveData: '', // 预存保存后的数据
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      attachments: [],
      newData: {},

      // 收款码
      paymentCode: [],
      paymentApply: true,
    }
  },
  mounted() {
    //
  },
  methods: {
    getShareStateByCode(code) {
      const item = this.shareOptions.find(item => item.value == code)
      return item ? {label: item.label,color: item.color} : {}
    },
    onShowSupplierEdit() {
      this.newData = this.gysOptions.find(item => item.id == this.queryData.xghCompanyId)
      if(!this.newData){
        this.$elMessage.warning('请先选择客户')
        return
      } 
      // 0:是 1:否
      this.newData.companyInvoiceStatus = this.newData.companyInvoiceStatus == '0' ? true : false
      this.newData.companyRAndPStatus = this.newData.companyRAndPStatus == '0' ? true : false
      this.$refs.supplierAddRef.dialogVisible = true
    },
    supplementChange(val) {
      if (!val) {
        this.queryData.outTime = this.$formatDateTime()
      }
    },
    // 新增
    handleShortcutKeyAdd() {
      this.onNewOrder()
    },
    // 保存
    handleShortcutKeySave() {
      if (!this.buttonsPermissions.LuRu) {
        this.$elMessage.warning('未拥有保存权限！')
      } else if (this.saveBtnStatus) {
        this.$elMessage.warning('当前状态不支持保存操作！')
      } else {
        this.onSubmit()
      }
    },
    // 审核
    handleShortcutKeyExamine() {
      if (!this.buttonsPermissions.ShenHe) {
        this.$elMessage.warning('未拥有审核权限！')
      } else if (this.auditBtnStatus) {
        this.$elMessage.warning('当前状态不支持审核操作！')
      } else {
        this.onToExamine()
      }
    },
    // 打印
    handleShortcutKeyPrint() {
      if (!this.buttonsPermissions.DaYin) {
        this.$elMessage.warning('未拥有打印权限！')
      } else if (this.orderStatus == 66) {
        this.$elMessage.warning('当前状态不支持打印操作！')
      } else {
        console.log('快捷键打印-销售出库单')
        // 可以多次打印设置
        if (this.printPermissions) {
          this.$refs.print.show(this.printData, this.columnData, '销售出库单')
        } else {
          if (this.$lcStorage.get('printLimitValue')) {
            // 获取打印次数
            this.getPrintNum(this.billId, () => {
              this.$refs.print.show(this.printData, this.columnData, '销售出库单')
            })
          } else {
            this.$refs.print.show(this.printData, this.columnData, '销售出库单')
          }
        }
      }
    },
    beforeUpload(file) {
      let type = file.type.toLowerCase()
      const isJPG = type.includes('png') || type.includes('jpeg') || type.includes('jpg')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('请上传png/jpg/jpeg格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleSuccess(e) {
      console.log(e)
      if (e.success) {
        if (this.attachments.length < 5) {
          this.attachments.push(e.message)
        } else {
          this.$message.error('最多支持上传5张!')
        }
      }
    },
    delAttachment(index) {
      this.attachments.splice(index, 1)
    },
    focusSelect(e) {
      e.target.select()
    },
    // 获取数据 从销售订单复制过来
    getData() {
      this.getAccountData() // 获取账户信息数据
      this.getExpressList() //获取物流公司列表
      this.getGysStorage() //供应商数据
      this.getWarehouseData() // 获取所有仓库数据
      this.getStaffData() // 获取所有员工数据
      this.getFpOptions()
      this.selectTitle()
      // this.getConfig() // 获取收款码信息
      this.getApplyState() // 获取申请状态
    },
    //查看单据详情
    getOrderDetailById() {
      getAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/getBuyOrderById', { id: this.billId }).then((res) => {
        if (res.success) {
          this.handleData(res.result)
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    /**
     * 初始化默认获取缓存中存储的曾经点击过的供应商数据
     */
    getGysStorage() {
      // getCompanyList().then((res) => {
      //   console.log(res);

      // })
      getAction('/xghCompany/xghCompany/listNoPage', {}).then((res) => {
        if (res.code === 200) {
          this.gysOptions = res.result
          this.totalCompanys = res.result
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    /**
     * 获取所有仓库数据
     */
    getWarehouseData() {
      getAction('/xghStorehouse/xghStorehouse/queryListByPole', {}).then((res) => {
        if (res.code === 200) {
          this.ckOptions = res.result
          this.ckOptions.forEach((item) => {
            if (item.isDefault == 1) {
              this.queryData.xghOutStorehouseId = item.id
            }
          })
          this.getXghStorehouseIdById(false)
          this.totalStores = res.result
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    /**
     * 获取所有员工数据
     */
    async getStaffData() {
      getAction('/dept/xghAccountBookDept/getAllDeptUsers', {}).then((res) => {
        if (res.code === 200) {
          this.jsrOptions = res.result
          this.totalPersons = res.result
          // 默认经手人设置
          this.queryData.sysUserId = this.$lcStorage.get('xghUser').id
        }
      })
    },
    /**
     * 获取账户信息数据
     */
    async getAccountData() {
      const data = await getAction('/xghBank/xghBank/listNoPage', {})
      if (data.code !== 200) {
        return this.$elMessage.error('获取数据失败！')
      }
      this.paymentData = []
      for (let i = 0; i < data.result.length; i++) {
        this.paymentData.push({
          xh: i + 1,
          id: data.result[i].id,
          bankName: data.result[i].bankName,
          isDefault: data.result[i].defaultFlag,
          price: 0,
          xhState: true,
        })
      }
    },
    /**
     * 获取账户信息数据
     */
    // async getPrintNum () {
    //   let userInfo = Vue.ls.get(USER_INFO)
    //   let paramVal = {
    //     userId: userInfo.id,
    //     orderId: this.billId
    //   }
    //   const data = await getAction('/xghuserorderprintrecord/xghUserOrderPrintRecord/getPrintNum', paramVal)
    //   if (data.code !== 200) {
    //     return this.$elMessage.error('获取数据失败！')
    //   }
    //   // 开启多次打印设置并且次数不为0
    //   let printLimitOptions = this.$lcStorage.get('printLimitOptions')
    //   if (!data.res || printLimitOptions >= data.result.printNum) {
    //     this.$refs.print.show(this.printData, this.columnData, '销售出库单')
    //   } else {
    //     this.$elMessage.warning('没有打印次数！')
    //   }
    // },
    /**
     * 获取单据
     */
    getBillRecord() {
      if (!this.queryData.xghCompanyId) {
        return
      }
      getAction('/xghCompany/xghCompany/getById', { companyId: this.queryData.xghCompanyId }).then((res) => {
        console.log('单据明细', res)
        if (res.code == 200) {
          this.billRecord = res.result || {}
          console.log(this.printData)
          this.printData.beforeDebt = this.billRecord.totalReceivable
          this.printData.totalDebt = Number(this.billRecord.totalReceivable) + Number(this.queryData.owePrice)
        }
      })
    },
    getFpOptions() {
      let config = sysConfig()
      this.fpOptions = [
        {
          id: '0',
          label: ' ',
          value: '0',
        },
        {
          id: '1',
          label: '收据',
          value: '00',
        },
        {
          id: '2',
          label: '普通发票',
          value: config.tax_rate,
        },
        {
          id: '3',
          label: '增值税发票',
          value: config.vat_rate,
        },
      ]
      this.taxRate = this.getTaxRate()
    },
    invoiceTypeChange() {
      this.taxRate = this.getTaxRate()
      this.$refs.newTableRef.updateTaxRate(this.taxRate)
    },
    getTaxRate() {
      let config = sysConfig()
      if (this.queryData.invoiceType == '0') {
        return 0
      } else if (this.queryData.invoiceType == '1') {
        return 0
      } else if (this.queryData.invoiceType == '2') {
        return parseInt(config.tax_rate)
      } else if (this.queryData.invoiceType == '3') {
        return parseInt(config.vat_rate)
      }
    },
    // 处理操作下拉列表的启用禁用项
    handleOperationData() {
      if (this.orderStatus == 66 || this.orderStatus == 0) {
        this.importValue = '导入'
      } else {
        this.importValue = '导出'
      }
      //orderStatus 订单状态：0待审核、5审核通过、10作废、15反审、20红冲、25终止、30完成
      let allList = ['作废', '反审', '红冲', '复制单据', '办理过程']
      let result = []
      if (this.orderStatus == 0 || this.orderStatus == 15) {
        // 保存/之后状态，可作废，不可反审、红冲，可保存
        if (this.buttonsPermissions.ZuoFei) {
          result = ['作废']
        }
      } else if (this.orderStatus == 5) {
        // 审核状态，不可作废，可反审、红冲，不可保存
        // 审核后
        if (this.buttonsPermissions.FanShen) {
          result.push('反审')
        }
        if (this.buttonsPermissions.HongChong) {
          result.push('红冲')
        }
      } else if (this.orderStatus == 10 || this.orderStatus == 20) {
        // 作废/红冲后状态，不可作废、反审、红冲，不可保存
      }
      if (this.orderStatus !== 66) {
        result = result.concat(['复制单据', '办理过程'])
      }

      let resultList = []
      allList.forEach((item) => {
        let newItem = {
          value: item,
          disabled: result.indexOf(item) == -1,
        }
        resultList.push(newItem)
      })
      this.operationData = resultList
    },
    /**
     * 获取物流公司列表
     */
    async getExpressList() {
      const data = await getAction('/xghExpress/xghExpress/listNoPage', {})
      if (data.code == '200') {
        this.wlgsOptions = data.result
        this.totalExpress = data.result
      }
    },
    expressStatusChange(e) {
      if (!e) {
        //清空
        this.queryData.expressStatus = false
        this.queryData.xghExpressId = '' //物流公司id
        this.queryData.expressNumber = '' //物流单号
        this.queryData.xghExpressDetailId = '' //物流代付信息id
        this.queryData.expressPayStatus = false //物流状态 1.运费已付 0.未付
        this.queryData.expressPayPrice = '0.00' //物流代付金额
        this.queryData.expressPrice = 0 //运费
        this.xghExpressDetail = {}
        this.collectionPayPage = {}
        this.expressPaymentEcho = []
      }
      this.handlePriceChange()
    },
    expressPayStatusChange(e) {
      let amount = this.queryData.expressPrice
      if (this.queryData.expressPayStatus && amount == 0) {
        this.$refs.simplePrompt.showFreight()
        setTimeout(() => {
          this.queryData.expressPayStatus = false
        }, 800)
      }
    },

    // 清空物流付款账户和多账户付款账户的记录数据
    clearPaymentData() {
      this.paymentEcho = {
        xghCollectionPayInfoList: [],
      }
      this.expressPaymentEcho = []
    },
    // 提醒弹框取消后操作
    onCancel(mark) {
      if (mark == 'onChangeCk') {
        // 改变仓库
        this.getXghStorehouseIdById(true)
      }
    },
    // 提醒弹框确认后操作
    onYes(mark) {
      if (mark == 'onNewOrder') {
        this.orderStatus = 0
        this.onNewOrder()
      } else if (mark == 'onUpper') {
        // 上一单
        this.switchoverBill(1)
      } else if (mark == 'onLower') {
        // 下一单
        this.switchoverBill(2)
      } else if (mark == 'onChangeCk') {
        // 改变仓库
        // 根据出货仓库选择商品里的仓库
        this.getXghStorehouseIdById(false)
      } else if (mark == 'onToExamine') {
        this.examineLoading = true
        // 审核
        this.updateOrder(5, 'audit')
      } else if (mark == 'onToVoid') {
        // 作废
        this.updateOrder(10, 'aborted')
      } else if (mark == 'onToHongC') {
        // 红冲
        this.$refs.simplePrompt.show({
          index: 1,
          text: '确定要红冲当前的业务单据吗？</br>注：对应的应付款记录将会被自动红冲',
        })
      } else if (mark == 'onToStop') {
        // 终止
        this.updateOrder(25)
      } else if (mark == 'onToFinish') {
        // 完成
        this.updateOrder(30)
      } else if (mark == 'onCopy') {
        // 复制单据
        this.onCopyBillData()
        this.$refs.simplePrompt.show({
          index: 0,
          text: '单据复制成功',
        })
      } else if (mark == 'onUnCheck') {
        this.checkReVerifyPermission()
      }
    },
    //移除当前单据的所有id，用于复制单据和反审单据
    onCopyBillData() {
      if (this.orderStatus != 66) {
        this.orderStatus = 66
        this.queryData.id = ''
        this.TableConfig.tableData.forEach((item) => {
          item.id = ''
          item.ignore = false
          item.compulsory = '0'
          item.callDocumentId = undefined
          item.callDocumentType = undefined
        })
        this.paymentEcho.id = ''
        this.paymentEcho.xghCollectionPayInfoList.forEach((item) => {
          item.id = ''
        })
        console.log(this.expressPaymentEcho)
        this.expressPaymentEcho.forEach((item) => {
          item.id = ''
          item.orderId = ''
        })
      }
      this.collectionPayPage.id = ''
      this.collectionPayPage.orderId = ''

      if (this.collectionPayPage && this.collectionPayPage.xghCollectionPayInfoList) {
        this.collectionPayPage.xghCollectionPayInfoList.forEach((item) => {
          item.id = ''
          item.orderId = ''
        })
      }

      this.xghExpressDetail.id = ''
      this.xghExpressDetail.orderId = ''

      this.billId = '' //单据ID置空
      this.logData.orderId = -1
      this.queryData.orderNumber = '' //单据编号置空
      this.queryData.orderIndex = '' //`
      this.queryData.buyOrderStatus_dictText = '' //单据状态置空
      this.queryData.xghExpressDetailId = ''

      this.queryData.putTime = this.$formatDateTime()
      this.queryData.createOrderDate = this.$formatDateTime()
      this.queryData.createName = this.$lcStorage.get('xghUser').realname
    },
    getHaveChange() {
      // //获取源数据，将订单状态置成新单状态
      let source = JSON.parse(JSON.stringify(this.$options.data().queryData))
      source.sysUserId = this.$lcStorage.get('xghUser').id
      this.ckOptions.forEach((item) => {
        if (item.isDefault == 1) {
          source.xghOutStorehouseId = item.id
        }
      })
      // // 获取现有数据，移除自动添加的值
      let current = JSON.parse(JSON.stringify(this.queryData))
      current.outTime = ''
      current.createOrderDate = ''
      current.createName = ''
      // // 判断当前数据是否和源数据相同，相同表示未做修改
      let sourceStr = JSON.stringify(source)
      let currentStr = JSON.stringify(current)
      // console.log(sourceStr);
      // console.log(currentStr);
      return sourceStr != currentStr
    },
    // 点击开新单
    onNewOrder() {
      this.$nextTick(() => {
        // 新单时，更新扩展字段数据
        this.$refs.extendedFieldsRef.updateTableData('new')
      })

      if (this.orderStatus === 66 && this.getHaveChange()) {
        this.tipsData.tipsWords = '当前单据还未保存，</br>是否继续？'
        this.tipsData.tipsMark = 'onNewOrder'
        this.$refs.reminderRef.dialogVisible = true
      } else {
        this.orderFlag = 0
        this.pageNo = 0
        this.pageTotal = 1
        this.orderStatus = 66
        this.billId = ''
        this.logData.orderId = -1
        this.queryData = JSON.parse(JSON.stringify(this.$options.data().queryData))
        this.taxRate = 0 // 重置税率
        this.ckOptions.forEach((item) => {
          if (item.isDefault == 1) {
            this.queryData.xghOutStorehouseId = item.id
          }
        })
        // 送货数量默认为0
        // this.queryData.deliverNum = 0

        this.attachments = []
        this.queryData.outTime = this.$formatDateTime()
        this.queryData.createOrderDate = this.$formatDateTime()
        this.queryData.createName = this.$lcStorage.get('xghUser').realname
        // 默认经手人设置
        this.queryData.sysUserId = this.$lcStorage.get('xghUser').id
        this.isCreditLimit = false
        this.negativeInventory = false
        this.paymentEcho = {}
        this.xghExpressDetail = {}
        this.collectionPayPage = {}
        this.$nextTick(() => {
          this.$refs.newTableRef.getSubData()
          this.$refs.newTableRef.onResetCommodity()
        })
      }
    },
    showTips(msg) {
      this.$elMessage({
        showClose: true,
        message: msg || '',
        type: 'error',
        iconClass: 'el-icon-warning-outline',
        duration: 3000,
      })
    },
    priceZeroCallback(data) {
      if (data.type == 'once') {
        this.TableConfig.tableData[data.index].ignore = true
        this.showPriceZeroDialog = false
        this.onSubmit()
      } else if (data.type == 'cancel') {
        this.showPriceZeroDialog = false
      } else if (data.type == 'all') {
        for (let index = 0; index < this.TableConfig.tableData.length; index++) {
          let element = this.TableConfig.tableData[index]
          element.ignore = true
        }
        this.showPriceZeroDialog = false
        this.onSubmit()
      }
    },
    getZeroByGoods() {
      let list = this.TableConfig.tableData
      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (element.salePrice == formatPrice(0) && !element.ignore && !element.isGive) {
          this.showPriceZeroDialog = true
          let item = {
            id: element.id,
            name: `商品[${element.goodsName}]销售单价`,
            index,
          }
          this.priceZeroGoodsData = item
          return true
        }
      }
      return false
    },
    priceBelowCallback(data) {
      console.log(data)
      if (data.type == 'cancel') {
        this.showPriceBelowDialog = false
      } else {
        if (data.index == 1) {
          this.showPriceBelowDialog = false
          this.isCreditLimit = true
          this.onSubmit()
        } else {
          this.showPriceBelowDialog = false
          for (let index = 0; index < this.TableConfig.tableData.length; index++) {
            let element = this.TableConfig.tableData[index]
            element.compulsory = '1'
          }
          this.onSubmit()
        }
      }
    },
    getBelowByGoods() {
      let list = this.TableConfig.tableData
      let goodsName = ''
      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (delcommafy(element.salePrice) < parseFloat(element.costPrice) && element.compulsory == 0) {
          if (goodsName.length == 0) {
            goodsName = element.goodsName
          } else {
            goodsName = goodsName + '，' + element.goodsName
          }
        }
      }
      if (goodsName.length > 0) {
        this.showPriceBelowDialog = true
        let item = {
          id: '',
          name: `商品[${goodsName}]销售单价低于成本价`,
          index: 0,
        }
        this.priceBelowGoodsData = item
        return true
      }
      return false
    },
    negativeInventoryCallBack(data) {
      if (data.type == 'cancel') {
        this.showNegativeInventoryDialog = false
      } else {
        this.showNegativeInventoryDialog = false
        this.negativeInventory = true
        if (data.index == 1) {
          this.onSubmit()
        } else if (data.index == 2) {
          // 继续审核
          this.updateOrder(5, 'audit')
        } else if (data.index == 3) {
          // 继续红冲
          this.updateOrder(20)
        }
      }
    },
    // 保存
    async onSubmit() {
      // 先判断是否有修改或录入权限
      if (this.billId) {
        if (!this.buttonsPermissions.XiuGai) {
          this.showTips('没有修改权限！')
          return
        }
      }
      if (!this.queryData.xghCompanyId) {
        this.$elMessage.warning('客户不能为空，请选择！')
        return
      }
      if (!this.queryData.xghOutStorehouseId) {
        this.$elMessage.warning('出货仓库不能为空，请选择！')
        return
      }
      if (this.queryData.expressPrice > 0 && !this.queryData.xghExpressId) {
        this.$elMessage.warning('物流运费不为0，请选择物流公司！')
        return
      }
      if (this.queryData.expressPayPrice > 0 && !this.queryData.xghExpressId) {
        this.$elMessage.warning('代收金额不为0，请选择物流公司！')
        return
      }

      if (!this.isInputSkip) {
        if (this.getZeroByGoods()) {
          return
        }
      }
      if (this.isBelowCost) {
        if (this.getBelowByGoods()) {
          return
        }
      }

      let queryObj = JSON.parse(JSON.stringify(this.queryData))

      let count = 0
      let digest = []
      let newTableData = JSON.parse(JSON.stringify(this.TableConfig.tableData))
      let list = newTableData
        .map((item) => {
          if (item.goodsId) {
            item.isGift = item.isGive ? '0' : '1' //赠品0:是赠品1：不是赠品
            item.salePrice = formatFour(delcommafy(item.salePrice))
            item.allPrice = formatFour(delcommafy(item.allPrice))
            item.discountUnitPrice = formatFour(delcommafy(item.discountUnitPriceShow))
            item.taxUnitPrice = formatFour(delcommafy(item.taxUnitPrice))
            item.taxPrice = formatFour(delcommafy(item.taxPrice))
            item.salePriceShow = formatPrice(delcommafy(item.salePrice))
            item.allPriceShow = formatMoney(delcommafy(item.allPrice))
            item.discountUnitPriceShow = formatPrice(delcommafy(item.discountUnitPrice))
            item.taxUnitPriceShow = formatPrice(delcommafy(item.taxUnitPrice))
            item.taxPriceShow = formatMoney(delcommafy(item.taxPrice))
            item.xghAccountBookId = this.accountBookId
            item.saleOrderType = '2' //单据类型1：入库2;出库
            if (Number(item.number) == 0) {
              count++
            }
            digest.push(`[${item.goodsName},${item.numberShow}${item.unit}]`)
            // 特殊功能
            if (item.attributeOrderInfoRequest) {
              item.attributeOrderInfoRequest.forEach((item1) => {
                item1.orderType = '6'
                item1.mainId = this.billId
                item1.price = item.taxUnitPrice
                item1.accountBookId = this.accountBookId
                item1.outStoreId = item.xghStorehouseId
                item1.outNumber = item1.number
              })
            }
            return item
          }
        })
        .filter((item) => {
          return item != undefined
        })
      if (list.length == 0) {
        this.$elMessage.warning('商品不能为空，请选择商品！')
        return
      } else if (count > 0) {
        this.$elMessage.warning('商品数量不能为0')
        return
      }

      let orderObj = {
        ...queryObj,
        attachment: this.attachments.join(','), //附件
        summary: digest.join(';'), //摘要
        isReplacementOrder: queryObj.isSupplement ? '0' : '1',
        expressStatus: queryObj.expressStatus ? '0' : '1', //物流状态-0：开启 1:关闭
        expressPayStatus: queryObj.expressPayStatus ? '1' : '2', //物流费付款状态1：已付款，2：未付
        orderDiscountPrice: delcommafy(queryObj.orderDiscountPrice), //移除需要参与计算的数值千分位分隔符
        owePrice: delcommafy(queryObj.owePrice),
        collectionPrice: delcommafy(queryObj.collectionPrice),
        allPrice: delcommafy(queryObj.allPrice),
        receivablePrice: delcommafy(queryObj.receivablePrice),
        expressPayPrice: delcommafy(queryObj.expressPayPrice),
        status: 0, //完成状态0.待审核5.审核通过10.作废15.反审20.红冲25.终止30.完成
        xghAccountBookId: this.accountBookId,
        xghSaleStorehouseOrderInfoList: list,
        compulsoryCredit: this.isCreditLimit ? '1' : '0',
        negativeInventory: this.isBaseVersion ? '1' : this.negativeInventory ? '1' : '0',
        createOrderDate: this.billId ? queryObj.createOrderDate : '',
      }

      // 整单优惠金额不能大于合计金额
      if (orderObj.orderDiscountPrice > orderObj.allPrice) {
        this.$elMessage.warning('整单优惠金额不能大于合计金额')
        return
      }
      //物流代付金额不能大于应付金额
      if (orderObj.expressPayPrice > orderObj.receivablePrice) {
        this.$elMessage.warning('物流代收金额不能大于应收金额')
        return
      }
      //本次付款金额不能大于应付金额
      if (orderObj.collectionPrice > orderObj.receivablePrice) {
        this.$elMessage.warning('本次收款金额不能大于应收金额')
        return
      }
      //物流代付金额和本次付款不能大于应付金额
      if (orderObj.collectionPrice + orderObj.expressPayPrice > orderObj.receivablePrice) {
        this.$elMessage.warning('物流代收金额和本次收款金额不能大于应收金额')
        return
      }
      if (orderObj.collectionPrice != 0 && !orderObj.bankName) {
        this.$elMessage.warning('本次收款金额不为0时账户信息不能为空')
        return
      }

      //物流代收信息
      let expressCollectionPayPage = null
      if (this.queryData.xghExpressDetailId || orderObj.expressPayPrice > 0) {
        expressCollectionPayPage = {
          companyId: orderObj.xghExpressId, //物流公司id
          companyType: 1, //单位类型1:快递收付 2;往来单位收付
          isBegin: 1,
          isDeposit: 1,
          orderType: '32', //32代收  33代付  34物流运费
          payType: 1, //收付类型1:收款2：付款
          balance: orderObj.expressPayPrice,
          status: 0, //结销状态0：未结1：部分结销2:已结销
          settlementStatus: '0', //结算单状态0保存 5.审核 20 红冲
          xghAccountBookId: this.accountBookId,
          id: this.queryData.xghExpressDetailId,
          receivablePrice: orderObj.expressPayPrice,
          price: orderObj.expressPayPrice,
        }
      }
      //物流运费信息
      let expressList = JSON.parse(JSON.stringify(this.expressPaymentEcho))
      if (expressList) {
        expressList.forEach((item) => {
          item.xghAccountBookId = this.accountBookId
          item.isPay = orderObj.expressPayStatus //物流费付款状态1：已付款，2：未付
          item.xghExpressId = orderObj.xghExpressId
          item.orderId = this.billId
          ;(item.expressNumber = this.queryData.expressNumber), (item.payType = 2) //收付类型1:收款2：付款
        })
      }

      let bankids = expressList.map((item) => {
        return item.bankId
      })
      let xghExpressDetail = {
        ...this.xghExpressDetail,
        bankId: bankids.join(','),
        receivablePrice: orderObj.expressPrice,
        expressNumber: orderObj.expressNumber,
        expressPrice: orderObj.expressPrice,
        expressType: '2',
        payType: 2, //运费，物流运费都是要付款，传2
        isPay: orderObj.expressPayStatus, //物流费付款状态1：已付款，2：未付
        orderId: this.billId,
        xghAccountBookId: this.accountBookId,
        collectionPrice: orderObj.expressPayPrice,
        settlementStatus: '0',
        companyId: this.queryData.xghCompanyId,
        companyType: '1', //单位类型1:快递收付 2;往来单位收付3：银行账户id
        orderType: '6', //随主单据
        status: queryObj.expressPayStatus ? '2' : '0', //结销状态0：未结1：部分结销2:已结销
        price: orderObj.expressPayPrice,
        xghExpressId: orderObj.xghExpressId,
      }

      let xghExpressDetailVo = undefined
      let collectionPayPage = undefined
      if (orderObj.expressPrice && orderObj.expressPrice != 0) {
        collectionPayPage = {
          ...xghExpressDetail,
          id: this.collectionPayPage.id || '',
          orderId: this.collectionPayPage.orderId || '',
          orderType: '34', //32代收  33代付  34物流运费
          companyId: orderObj.xghExpressId,
          xghCollectionPayInfoList: expressList,
          balance: queryObj.expressPayStatus ? 0 : orderObj.expressPrice,
          settlementPrice: queryObj.expressPayStatus ? orderObj.expressPrice : 0,
        }
      }
      if (orderObj.expressStatus) {
        xghExpressDetailVo = {
          collectionPayPage,
          xghExpressDetail: xghExpressDetail,
        }
      }

      // 本次收款 collectionPrice 单据金额  receivablePrice
      let p = delcommafy(orderObj.receivablePrice)
      let d = delcommafy(this.queryData.collectionPrice)
      let status = '0'
      if (p == 0 || p == d) {
        status = '2'
      } else if (d < p && d > 0) {
        status = '1'
      }
      //支付信息
      let payObj = {
        ...this.paymentEcho,
        isBegin: 1, //是否期初0：是期初 1：不是
        isDeposit: 1, //是否定金0:是1:不是
        payType: 1, //收付类型1:收款2：付款
        price: delcommafy(this.queryData.collectionPrice),
        orderType: '6', //采购订单1/采购入库单2/采购退货单3/采购换货单4/销售订单5/销售出库单6/销售退货单7/销售换货单8/盘点单9/报损单10
        companyId: this.queryData.xghCompanyId,
        companyType: '2', //单位类型1:快递收付 2;往来单位收付
        xghAccountBookId: this.accountBookId,
        settlementStatus: '0', //结算单状态0保存 5.审核 20 红冲
        status, //结销状态0：未结1：部分结销2:已结销
        receivablePrice: delcommafy(orderObj.receivablePrice), //应收金额
        balance: delcommafy(orderObj.receivablePrice) - delcommafy(orderObj.expressPayPrice),
        collectionPrice: orderObj.expressPayPrice || '0.00',
        documentsName: this.pageName,
        documentsType: this.getBillTypeByText(this.pageName),
      }
      orderObj.closingStatus = status //单据信息携带结销状态


      // 处理扩展字段多选时的选项
      const submitExtendFields = JSON.parse(JSON.stringify(this.$refs.extendedFieldsRef.getTableData()))
      submitExtendFields.forEach((item) => {
        if (item.fieldType === 'selectMultiple' && Array.isArray(item.fieldValue)) {
          console.log(item.fieldValue, '进入循环了')
          item.fieldValue = item.fieldValue.join(',')
        }
      })
      // 总信息
      let obj = {
        collectionPayPage: payObj, //
        saleStorehouseOrderPage: orderObj,
        // expressDetailList: expressList,
        expressCollectionPayPage,
        xghExpressDetailVo,
        extendFields: submitExtendFields,
      }
      console.log('保存：', obj)

      var res = {}
      // 修改
      if (this.billId) {
        // 先判断用户是否拥有修改权限
        if (this.buttonsPermissions.XiuGai) {
          res = await putAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/edit', obj)
        } else {
          this.showTips('没有修改权限！')
          return
        }
      } else {
        // 新增
        res = await postAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/add', obj)
      }
      if (res.code === 200) {
        if (this.billId) {
          this.$elMessage.success('修改成功！')
        } else {
          this.$elMessage.success('新增成功！')
        }
        // this.tipsData.resultType = 1
        // this.$refs.successRef.dialogVisible = true
        this.handleData(res.result)
        this.isCreditLimit = false
        this.negativeInventory = false
        this.toSaveOrExamine()

        this.$EventBus.$emit('update-data', {
          isOnSubmit: 1
        })

        // 保存后更新扩展字段
        this.$refs.extendedFieldsRef.updateTableData(res.result.extendFields)
      } else if (res.code == 303) {
        this.showPriceBelowDialog = true
        let item = {
          id: '',
          name: `商品${res.message}销售单价低于成本价`,
          index: 0,
        }
        this.priceBelowGoodsData = item
      } else if (res.code == 101) {
        this.showPriceBelowDialog = true
        let item = {
          id: '',
          name: `${res.message}`,
          index: 1,
        }
        this.priceBelowGoodsData = item
      } else if (res.code == 48) {
        let config = sysConfig()
        let show = false
        let name = ''
        if (config.allow_negative_inventory) {
          // 允许负库存
          show = true
          name = `商品${res.message}库存不足, 是否继续保存?`
        } else {
          show = false
          name = `商品${res.message}库存不足, 并且不允许负库存, 无法进行保存!`
        }
        this.showNegativeInventoryDialog = true
        let item = {
          id: '',
          name: name,
          index: 1,
          show: show,
        }
        this.negativeInventoryData = item
      } else {
        this.showTips(res.message)
      }
    },

    // 当操作成功后点击了确定按钮之后进行的下一步操作：
    onOptionSuccess() {
      // if (this.tipsData.resultType == 1) {
      //   this.tipsData.resultType == -1
      //   // 保存成功了
      //   console.log('操作成功后点击确定按钮了')
      //   this.toSaveOrExamine()
      // } else if (this.tipsData.resultType == 2) {
      //   this.tipsData.resultType == -1
      //   // 审核成功了
      //   console.log('审核成功后点击确定按钮了')
      //   this.afterExamine()
      // }
    },
    // 单据保存后的走向
    toSaveOrExamine() {
      if (this.isSaveExamine && this.buttonsPermissions.ShenHe) {
        // 保存后立即审核,且有审核权限
        setTimeout(() => {
          this.onToExamine()
        }, 1000)
      } else if (this.isSaveNewOrder && this.buttonsPermissions.LuRu) {
        // 如果保存后立即开新单,并且有新增权限
        this.onYes('onNewOrder')
      }
    },
    afterExamine() {
      // 如果审核后立即开新单
      if (this.isExamineNewOrder && this.buttonsPermissions.LuRu) {
        this.onYes('onNewOrder')
      }
    },
    // 审核单据
    onToExamine() {
      let queryData = JSON.parse(JSON.stringify(this.queryData))
      let tableData = JSON.parse(JSON.stringify(this.TableConfig.tableData))
      queryData.xghSaleStorehouseOrderInfoList.forEach((item) => {
        item.discountRate = Number(item.discountRate)
        // delete item['unitList']
        delete item['visible']
      })
      tableData.forEach((item) => {
        item.discountRate = Number(item.discountRate)
        // delete item['unitList']
        delete item['visible']
      })

      var data = JSON.parse(
        JSON.stringify({
          ...queryData,
          ...tableData,
        })
      )
      // console.log(this.saveData);
      // console.log(data);
      console.log(JSON.stringify(data))
      console.log(JSON.stringify(this.saveData))
      // console.log(JSON.stringify(data) === JSON.stringify(this.saveData))
      if (JSON.stringify(data) === JSON.stringify(this.saveData)) {
        this.tipsData.tipsWords = '确定要审核当前的单据吗？'
        this.tipsData.tipsMark = 'onToExamine'
        this.$refs.reminderRef.dialogVisible = true
      } else {
        this.$elMessage.warning('请先保存！')
      }
    },
    // 操作选择
    operationSelect(value) {
      switch (value) {
        case '作废':
          this.tipsData.tipsWords = '确定要作废当前的单据吗？'
          this.tipsData.tipsMark = 'onToVoid'
          this.$refs.reminderRef.dialogVisible = true
          break
        case '反审':
          // this.checkReVerifyPermission()
          this.tipsData.tipsWords = '确定要反审当前的单据吗？'
          this.tipsData.tipsMark = 'onUnCheck'
          this.$refs.reminderRef.dialogVisible = true
          break
        case '红冲':
          // this.tipsData.tipsWords = '确定要红冲当前的单据吗？'
          // this.tipsData.tipsMark = 'onToHongC'
          // this.$refs.reminderRef.dialogVisible = true
          // 红冲
          this.$refs.simplePrompt.show({
            index: 1,
            text: '确定要红冲当前的业务单据吗？</br>注：对应的应付款记录将会被自动红冲',
          })
          break
        case '终止':
          this.tipsData.tipsWords = '确定要终止当前的单据吗？'
          this.tipsData.tipsMark = 'onToStop'
          this.$refs.reminderRef.dialogVisible = true
          break
        case '完成':
          this.tipsData.tipsWords = '确定要完成当前的单据吗？'
          this.tipsData.tipsMark = 'onToFinish'
          this.$refs.reminderRef.dialogVisible = true
          break
        case '复制单据':
          this.tipsData.tipsWords = '确定要复制当前的单据吗？'
          this.tipsData.tipsMark = 'onCopy'
          this.$refs.reminderRef.dialogVisible = true
          break
        case '办理过程':
          this.$refs.operationLogRef.getData(this.logData)
          this.logTitle = '办理过程'
          this.$refs.operationLogRef.dialogVisible = true
          break
        default:
          break
      }
      this.operationValue = '操作'
    },
    // 调单选择
    exchangeSelect(item) {
      //['调用销售订单', '调用采购入库单', '调用调拨单'],
      console.log(item)
      switch (item) {
        case '调用销售订单':
          this.$refs.transferBill.show({
            title: '销售订单',
            api: '调单-销售订单',
            detailApi: '调单-销售订单明细',
            listUrl: '/xghSaleOrder/xghSaleOrder/list', //销售订单列表
            detailUrl: '/xghSaleOrder/xghSaleOrder/getOrderById', //销售订单明细
            orderKey: 'saleOrderPage',
            goodsListKey: 'xghSaleOrderInfoList',
            xghCompanyId: this.queryData.xghCompanyId,
            orderStatusKey: 'orderState',
          })
          break
        case '调用采购入库单':
          this.$refs.transferBill.show({
            title: '采购入库单',
            api: '调单-采购入库单',
            detailApi: '调单-采购入库单明细',
            listUrl: '/xghBuyOrder/xghBuyOrder/list', //采购入库列表
            detailUrl: '/xghBuyOrder/xghBuyOrder/getBuyOrderById', //采购订单明细
            orderKey: 'buyOrderPage',
            goodsListKey: 'xghBuyOrderInfoList',
            xghCompanyId: this.queryData.xghCompanyId,
            orderStatusKey: 'buyOrderStatus',
          })
          break
        case '调用调拨单':
          this.$refs.transferBill.show({
            title: '调拨单',
            api: '调单-调拨单',
            detailApi: '调单-调拨单明细',
            listUrl: '/xghAllotOrder/xghAllotOrder/queryList', //调拨单列表
            xghCompanyId: this.queryData.xghCompanyId,
            orderStatusKey: 'billOrderStatus',
            orderKey: 'buyOrderPage',
            goodsListKey: 'allotOrderInfoList',
          })
          break
        default:
          break
      }
      this.exchangeValue = '调单'
    },
    // 调单回调
    transferBillCallback(data) {

      let billObj = data.billObj
      let invoiceType = billObj.invoiceType || '0'
      if (invoiceType == '0') {
        invoiceType = this.queryData.invoiceType
      }

      this.queryData = {
        ...this.queryData,
        xghCompanyId: billObj.xghCompanyId,
        xghOutStorehouseId: billObj.xghStorehouseId || billObj.xghCStorehouseId,
        sysUserId: billObj.sysUserId,
        remark: `${billObj.remark || ''}${this.queryData.remark}`,
        invoiceType,
      }
      if (billObj.xghCompanyId) {
        let h = this.gysOptions.some((item) => item.id == billObj.xghCompanyId)
        if (!h) {
          this.getGysStorage()
        }
      }
      let goodsList = data.goodsList
      let index = this.TableConfig.tableData.length
      goodsList.forEach((val) => {
        let item = {
          ...val,
          isGive: val.isGive == '1' ? false : true, //赠品0:是赠品1：不是赠品
          // 2025-6-10 晨夕提出的，销售出库单调销售订单，带过来的数量为未发货数量
          // number: formatFour(val.number),
          // numberShow: formatNumber(val.number),
          number: formatNumber(val.notDeliverNumber != null ? val.notDeliverNumber : val.number),
          numberShow: formatNumber(val.notDeliverNumber != null ? val.notDeliverNumber : val.number),
          deliverNum: formatNumber(val.deliverNum),
          taxRate: val.taxRate || this.queryData.taxRate || this.taxRate,
          taxPriceShow: formatFour(val.taxPriceShow),
          salePrice: formatFour(val.salePrice || val.goodsPrice),
          allPrice: formatFour(val.allPrice),
          discountUnitPrice: formatFour(val.discountUnitPrice),
          taxUnitPrice: formatFour(val.taxUnitPrice),
          discountRate: val.discountRate || this.queryData.discountRate || 100,
          salePriceShow: formatPrice(val.salePrice || val.goodsPrice),
          allPriceShow: formatMoney(val.allPrice),
          discountUnitPriceShow: formatPrice(val.discountUnitPrice),
          taxUnitPriceShow: formatPrice(val.taxUnitPrice),
          unitList: val.goodsManyNorms,
          callDocumentId: val.callDocumentId,
          callDocumentType: val.callDocumentType,
           // 特殊功能
           attributeOrderInfoRequest: getAttributeOrderInfoRequest(val.attributeGoodsResponse, true),
          specialColorSize: (val.specialFunctionType || '').includes('1'),
          showSpeial: true
        }
        if (this.TableConfig.tableData.length == 1 && !this.TableConfig.tableData[0].goodsId) {
          this.TableConfig.tableData.splice(0, 1, item)
          index = 0
        } else {
          this.TableConfig.tableData.push(item)
        }
        this.$refs.newTableRef.handlePrice(index)
        index++
      })
      for (let index = 0; index < this.TableConfig.tableData.length; index++) {
        const element = this.TableConfig.tableData[index];
        if (element.formulaId) {
          this.$refs.newTableRef.formulaChange(element.formulaId, element, index) 
        } 
      }
    },
    // 导入
    importExcel() {
      this.$refs.daoru.dialogVisible = true
    },
    importData(val) {
      if (val.success) {
        this.$elMessage.success(val.message)
        let result = (val.result && val.result.records) || []
        result.map((item) => {
          item.goodsName = item.goodsId_dictText
          item.isGive = item.isGift == '0' ? true : false //赠品0:是赠品1：不是赠品
          item.unitList = item.goodsManyNorms
          item.unitScale = this.getUnitScale(item.goodsManyNorms, item.unit, 'scale')
          item.baseUnit = this.getUnitScale(item.goodsManyNorms, item.unit, 'id')

          item.xghStorehouseId = item.xghStorehouseId
          item.number = formatFour(item.number)
          item.numberShow = formatNumber(item.number)
          item.deliverNum = formatNumber(item.deliverNum),
          item.salePrice = formatFour(item.salePrice || item.goodsPrice)
          item.allPrice = formatFour(item.allPrice)
          item.discountUnitPrice = formatFour(item.discountUnitPrice)
          item.taxUnitPrice = formatFour(item.taxUnitPrice)

          item.salePriceShow = formatPrice(item.salePrice || item.goodsPrice)
          item.allPriceShow = formatMoney(item.allPrice)
          item.discountUnitPriceShow = formatPrice(item.discountUnitPrice)
          item.taxUnitPriceShow = formatPrice(item.taxUnitPrice)
          return item
        })

        if (this.TableConfig.tableData.length == 1 && !this.TableConfig.tableData[0].goodsId) {
          this.TableConfig.tableData = result
        } else {
          this.TableConfig.tableData = this.TableConfig.tableData.concat(result)
        }
      } else {
        this.$elMessage.error(val.message)
      }
    },
    getUnitScale(unitList, defaultUnit, key) {
      if (!unitList || !defaultUnit) {
        return '1'
      }
      for (let index = 0; index < unitList.length; index++) {
        const element = unitList[index]
        if (key == 'id' && element.isDefault) {
          return element.id
        } else if (key == 'scale' && element.unit == defaultUnit) {
          return element.scale
        }
      }
    },
    // 导出
    exportExcel(isTemplate = false) {
      let id = isTemplate ? '' : this.billId
      let queryParam = {
        fileName: this.pageName,
        orderId: id,
      }
      this.handleExportXlsByStaff(this.pageName, queryParam)
    },
    // 分享
    onShare() {
      if (!this.billId) {
        this.$elMessage.warning('未保存单据无法分享！')
      } else if (this.buttonsPermissions.FenXiang) {
        // let base = window._CONFIG['domianURL'].replace('api', '').replace('10030', '9047')
        // let bookId = Vue.ls.get(ACCOUNT_BOOK).id
        // let url = `${base}share?from=xsckd&aid=${bookId}&bid=${this.billId}`
        // window.open(url)
        this.getShareOrder().then(() => {
          let params = `billId=${this.billId}&billType=xsckd&orderType=6&share=${this.shareOrderNumber}`
          console.log("分享链接：",params)
          this.$refs.share.show(params)
        }).catch(() => {
          // this.$elMessage.warning('获取分享订单失败！')
          console.log('获取分享订单失败！')
        })
      } else {
        this.$elMessage.warning('没有分享权限！')
      }
    },
    // 获取收款码申请通过否 申请通过去获取支付状态 未支付添加订单
    getShareOrder() {
      return getAction('/xghRequestForm/xghRequestForm/getAuditStatusByAccountBookId', {
        accountBookId: this.accountBookId,
      }).then((res) => {
        if (res.code === 200) {
          if(res.result){
            return this.getPaymentStatus()
          }else{
            return Promise.resolve();
          }
        } else {
          return Promise.reject();
        }
      })
    },
    // 获取支付状态
    getPaymentStatus() {
      return getAction('/xghShareOrderPaymentOrders/xghShareOrderPaymentOrders/orderPaymentStatus', {
        orderId: this.billId,
        orderType:6,
      }).then((res) => {
        if (res.success) {
          if(res.result){
            return Promise.resolve();
          }else{
            return this.addShareOrder()
          }
        } else {
          this.$elMessage.warning(res.message)
          return Promise.reject();
        }
      })
    },
    // 添加分享订单
    addShareOrder() {
      return postAction('/xghShareOrderPaymentOrders/xghShareOrderPaymentOrders/add', {
        accountBookId:Vue.ls.get(ACCOUNT_BOOK).id,
        orderId: this.billId,
				orderType:6,
        orderMoney: delcommafy(this.formatReceivablePrice),
      }).then((res) => {
        if (res.success) {
          this.shareOrderNumber = res.result.orderNumber
          return Promise.resolve();
        } else {
          this.$elMessage.warning(res.message)
          return Promise.reject();
        }
      })
    },
    onShareResult() {
      if (!this.billId) {
        this.$elMessage.warning('未保存单据无法查看！')
      } else if (this.buttonsPermissions.FenXiang) {
        this.$refs.share.showResult(this.billId, this.queryData.xghCompanyId_dictText)
      } else {
        this.$elMessage.warning('没有分享权限无法查看！')
      }
    },
    // 单据核对
    onCheckBill() {
      let list = []
      let ids = []
      for (let index = 0; index < this.TableConfig.tableData.length; index++) {
        const item = this.TableConfig.tableData[index]
        let goodsId = item.goodsId
        if (ids.indexOf(goodsId) == -1) {
          ids.push(item.goodsId)
          list.push({
            goodsCode: item.goodsCode,
            goodsName: item.goodsName,
            number: item.number,
          })
        } else {
          let index = ids.indexOf(goodsId)
          list[index].number += item.number
        }
      }
      this.$refs.billContrast.show(list)
    },
    // 点击修改表样式
    onClickTable(row) {
      this.tableData.forEach((item) => {
        if (item.id == row.id) {
          item.xhState = false
        } else {
          item.xhState = true
        }
      })
    },

    // 当前选择商品数据
    onSelectCommodity(val) {
      if (this.$lcStorage.get('spHistoricalRecords')) {
        let arr = this.$lcStorage.get('spHistoricalRecords')
        arr.unshift(val)
        this.$lcStorage.set('spHistoricalRecords', arr)
      } else {
        let arr = [val]
        this.$lcStorage.set('spHistoricalRecords', arr)
      }
      let threeArr = this.selectDataHas(this.$lcStorage.get('spHistoricalRecords'))
      this.$lcStorage.set('spHistoricalRecords', threeArr)
      this.tableData.forEach((item) => {
        if (!item.xhState) {
          for (const key in item) {
            item[key] = val[key]
          }
        }
      })
    },
    // 打开选择物流运费支付弹出框
    onShowDialogPaymentWl() {
      // 标识物流运费弹出窗
      this.paymentType = '1'
      this.$refs.paymentRef.dialogVisible = true
      this.paymentTitleName = '物流运费多账户'
      // 调用子组件的处理数据回显方法，给组件赋值,数据源两次改变，初始值为先，处理金额回显在后，需延时处理
      setTimeout(() => {
        this.$refs.paymentRef.handleDataEcho(this.expressPaymentEcho)
      }, 100)
    },
    // 打开选择多账户支付弹出框
    onShowDialogPaymentZh() {
      // 调用子组件的处理数据回显方法，给组件赋值，数据源两次改变，初始值为先，处理金额回显在后，需延时处理
      this.$refs.paymentRef.dialogVisible = true
      this.paymentTitleName = '多账户'
      this.paymentType = '2'
      setTimeout(() => {
        this.$refs.paymentRef.handleDataEcho(this.paymentEcho.xghCollectionPayInfoList)
      }, 100)
    },
    // 显示扫码弹出框
    onShowScan() {
      this.$refs.scanPopover.style.display = 'flex'
    },
    // 新增数据中表格内输入框聚焦时选中
    focusinSelect() {
      event.target.select()
    },
    // 查询
    async selectTitle() {
      let obj = await this.$setColumn.selectColumn(this.url.api)
      let gObj = await this.$setColumn.selectColumn('商品信息')
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.TableConfig.columnData = obj.columnData
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.url.api, this.TableConfig.columnData, 0, this.updateId)
        this.updateId = id
      }
      let defaultlist = this.$options.data().TableConfig.columnData
      if (gObj.code === 200) {
        let list = gObj.columnData
        console.log(list);
        console.log(this.TableConfig.columnData);
        list.forEach(element => {
          if (element.props.includes('extendField')) {
            if (this.TableConfig.columnData[element.props]) {
              this.TableConfig.columnData[element.props].zidingyiName = element.zidingyiName
            }
            if (defaultlist[element.props]) {
              defaultlist[element.props].zidingyiName = element.zidingyiName
            }
          }
        });
        this.defaultColumnData = handleObjectToArray(defaultlist)
      }
    },
    // 列配置修改后数据获取
    async onSaveColumn(value) {
      this.TableConfig.columnData = handleArrayToObject(value, 'props')
      let res = await this.$setColumn.editColumn(this.url.api, this.TableConfig.columnData, this.updateId)
      if (res.code == 200) {
        this.$elMessage.success(res.message)
      } else {
        this.$elMessage.error(res.message)
      }
    },
     // 打开列配置弹框
     onShowColumn() {
      // this.defaultColumnData = handleObjectToArray(this.$options.data().TableConfig.columnData)
      this.$refs.setColumnRef.dialogVisible = true
    },
    onUpdateColumn() {
      this.onSaveColumn(handleObjectToArray(this.TableConfig.columnData))
    },
    // 列宽发生变化时触发
    onDragColumn(val) {
      this.$setColumn.editColumn(this.url.api, this.TableConfig.columnData, this.updateId)
    },
    // 单位改变触发
    onHandleUnit(val, i, transmit) {
      let sc = this.TableConfig.tableData[i].unitScale
      let sc1 = this.getUnitScale(val.unitList, val.unit, 'scale')
      this.TableConfig.tableData[i].unitScale = sc1
      this.TableConfig.tableData[i].baseUnit = this.getUnitScale(val.unitList, val.unit, 'id')
      if (sc && sc > sc1) {
        this.TableConfig.tableData[i].costPrice = this.TableConfig.tableData[i].costPrice / sc
      }else {
        this.TableConfig.tableData[i].costPrice = accMul(this.TableConfig.tableData[i].costPrice, sc1)
      }
      // 设置价格的默认值
      this.$refs.newTableRef.focusPrice('', i, this.TableConfig.tableData[i], transmit)
    },
    // 修改附记
    async updatePostScript() {
      let orderStateNum = Number(this.orderStatus)
      if (orderStateNum >= 5 && orderStateNum < 66) {
        const res = await getAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/addPostScript', {
          orderId: this.billId,
          postscript: this.queryData.postscript,
        })
        if (res.code == 200) {
          this.$elMessage.success('附记修改成功！')
        } else if (res.code === 500) {
          this.$elMessage.error(res.message)
        }
      }
    },
    /**
     * 父组件处理子组件获取到的商品信息数据字段名不统一问题
     * @param tableData 子组件中表格的数据
     * @param index 当前选中this.TableConfig.tableData的索引
     * @param val 从商品表中选中的商品数据
     */
    onHandleSpData(tableData, index, val) {
      // 根据出货仓库选择商品里的仓库
      for (const key in tableData[index]) {
        // this.TableConfig.tableData[index][key] = val[key]
        this.TableConfig.tableData[index].goodsNumber = val.goodsNumber
        this.TableConfig.tableData[index].goodsCode = val.barCode
        this.TableConfig.tableData[index].goodsId = val.id
        this.TableConfig.tableData[index].goodsName = val.goodsName
        this.TableConfig.tableData[index].norms = val.specs
        this.TableConfig.tableData[index].unit = val.defaultUnit
        this.TableConfig.tableData[index].unitList = val.goodsManyNorms
        this.TableConfig.tableData[index].xghStorehouseId = this.queryData.xghOutStorehouseId
        this.TableConfig.tableData[index].number = formatFour(val.number)
        this.TableConfig.tableData[index].numberShow = formatNumber(val.number)
        this.TableConfig.tableData[index].deliverNum = formatNumber(val.deliverNum),
        this.TableConfig.tableData[index].isGive = false
        this.TableConfig.tableData[index].remark = val.goodsRemark
        this.TableConfig.tableData[index].salePrice = formatFour(val.salePrice)
        this.TableConfig.tableData[index].allPrice = formatFour(val.salePrice)
        this.TableConfig.tableData[index].discountUnitPrice = formatFour(val.salePrice)
        this.TableConfig.tableData[index].taxUnitPrice = formatFour(val.salePrice)
        this.TableConfig.tableData[index].salePriceShow = formatPrice(val.salePrice)
        this.TableConfig.tableData[index].allPriceShow = formatMoney(val.salePrice)
        this.TableConfig.tableData[index].discountUnitPriceShow = formatPrice(val.salePrice)
        this.TableConfig.tableData[index].taxUnitPriceShow = formatPrice(val.salePrice)
        this.TableConfig.tableData[index].ignore = false
        this.TableConfig.tableData[index].useNumber = val.useNumber
        this.TableConfig.tableData[index].compulsory = '0'
        this.TableConfig.tableData[index].costPrice = val.costPrice
        this.TableConfig.tableData[index].taxRate = this.taxRate
        this.TableConfig.tableData[index].deliverNum = formatNumber(0)
        this.TableConfig.tableData[index].extendField1 = val.extendField1
        this.TableConfig.tableData[index].extendField2 = val.extendField2
        this.TableConfig.tableData[index].extendField3 = val.extendField3
        this.TableConfig.tableData[index].extendField4 = val.extendField4
        this.TableConfig.tableData[index].extendField5 = val.extendField5
        this.TableConfig.tableData[index].formulaList = val.formulaList
        //特殊功能
        this.TableConfig.tableData[index].specialFunctionType = val.specialFunctionType
        this.TableConfig.tableData[index].specialColorSize = (val.specialFunctionType || '').includes('1')
        this.TableConfig.tableData[index].showSpeial = val.showSpeial
      }

      //获取默认单位的换算比例
      let temp = {
        ...val,
        unitList: val.goodsManyNorms,
        unit: val.defaultUnit,
      }
      this.onHandleUnit(temp, index, false)
    },
    handlePriceChange() {
      // allPrice 总金额
      // receivablePrice 单据金额
      // orderRebate 整单折扣率
      // expressPayPrice 物流代付
      // orderDiscountPrice 整单优惠
      // payPrice 本次付款
      // owePrice 本次欠款

      let zje = delcommafy(this.queryData.allPrice)
      let djje = delcommafy(this.queryData.receivablePrice)
      let wldf = delcommafy(this.queryData.expressPayPrice)
      let zdyh = delcommafy(this.queryData.orderDiscountPrice)
      let bcfk = delcommafy(this.queryData.collectionPrice)

      // 单据金额 = 总金额  - 整单优惠
      // 本次欠款 = 单据金额 - 本次付款 - 物流代付
      djje = zje - zdyh
      let bcqk = djje - bcfk - wldf

      this.queryData.receivablePrice = formatMoney(djje)
      this.queryData.owePrice = formatMoney(bcqk)
    },
    // 商品总金额变化
    onHandleAllPrice(value) {
      this.queryData.allPrice = formatMoney(value)
      this.handlePriceChange()
    },
    // 整单优惠
    onChangeOrderDiscountPrice() {
      this.handlePriceChange()
    },
    //整单折扣
    onChangeDiscount() {
      if (this.queryData.orderRebate <= 0 || this.queryData.orderRebate > 100) {
        this.queryData.orderRebate = 100
      }
      this.TableConfig.tableData.forEach((item, index) => {
        item.discountRate = this.queryData.orderRebate
      })
      this.$refs.newTableRef.updatePrice()
    },
    // 本次付款
    onChangepayPrice(val) {
      let nIt = {
        companyId: this.queryData.xghCompanyId,
        companyType: 2, //单位类型1:快递收付 2;往来单位收付3：银行账户id
        isBegin: 1, //是否期初0：是期初 1：不是
        payType: 1, //收付类型1:收款2：付款
        price: val,
        xghAccountBookId: this.accountBookId,
      }
      // 如果当前修改了预付定金的值
      if (val && val > 0) {
        let haveDetault = false

        for (let i = 0; i < this.paymentData.length; i++) {
          // 则判断支付账户中哪个是默认账户
          if (this.paymentData[i].isDefault) {
            haveDetault = true
            this.queryData.bankName = this.paymentData[i].bankName // + ' ' + this.paymentData[i].paymentAmount
            nIt.bankId = this.paymentData[i].id
            nIt.bankName = this.paymentData[i].bankName
          }
        }
        if (!haveDetault && this.paymentData.length) {
          this.queryData.bankName = this.paymentData[0].bankName
          nIt.bankId = this.paymentData[0].id
          nIt.bankName = this.paymentData[0].bankName
        }
        this.paymentEcho.xghCollectionPayInfoList = [nIt]
      } else {
        this.paymentEcho.xghCollectionPayInfoList = []
      }
      this.queryData.collectionPrice = formatMoney(val)
      this.handlePriceChange()
    },
    // 物流代收确定后
    onSureExpressPrice() {
      this.queryData.expressPayPrice = formatPrice(this.queryData.expressPayPrice)
      this.handlePriceChange()
    },
    //运费变化
    expressProceBlur() {
      this.queryData.expressPrice = Math.abs(this.queryData.expressPrice)
      this.expressPaymentEcho = []
      if (this.queryData.expressPrice) {
        let nIt = {
          companyId: this.queryData.xghCompanyId,
          companyType: 1, //单位类型1:快递收付 2;往来单位收付3：银行账户id
          expressPrice: this.queryData.expressPrice,
          price: this.queryData.expressPrice,
          expressType: 6,
          receivablePrice: this.queryData.expressPrice,
        }
        let haveDetault = false
        for (let i = 0; i < this.paymentData.length; i++) {
          // 则判断支付账户中哪个是默认账户
          if (this.paymentData[i].isDefault) {
            haveDetault = true
            nIt.bankId = this.paymentData[i].id
            nIt.bankName = this.paymentData[i].bankName
            break
          }
        }
        if (!haveDetault && this.paymentData.length) {
          nIt.bankId = this.paymentData[0].id
          nIt.bankName = this.paymentData[0].bankName
        }
        this.expressPaymentEcho = [nIt]
        this.queryData.expressPayStatus = true
      } else {
        this.queryData.expressPayStatus = false
      }
    },
    /**
     * 获取当前单据数据
     */
    getOrderData(type) {
      // 清空物流付款账户信息
      this.clearPaymentData()
      let data = {
        type: '6', //采购订单1/采购入库单2/采购退货单3/采购换货单4/销售订单5/销售出库单6/销售退货单7/销售换货单8/盘点单9/报损单10
        orderFlag: this.orderFlag,
        pageSize: 1,
        pageNo: this.pageNo,
        orderId: this.billId || '',
      }
      getAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/preOrNextOrder', data).then(
        (res) => {
          this.lowerLoading = false
          this.upperLoading = false
          if (res.code === 200) {
            this.pageTotal = res.result.total || 1
            this.pageNo = res.result.current
            let list = res.result.records || []
            if (list.length) {
              // 处理请求到的数据
              this.handleData(list[0])
              // 获取当前单据的扩展字段，赋值给组件
              this.$nextTick(() => {
                console.log(this.$refs.extendedFieldsRef,'组件---')
                this.$refs.extendedFieldsRef.updateTableData(list[0].extendFields)
              })
            } else {
              if (type == 0) {
                this.$elMessage.warning('已经是第一条了')
              } else {
                this.$elMessage.warning('已经是最后一条了')
              }
            }
          } else if (res.code === 500) {
            this.showTips(res.message)
          }
        },
        (error) => {
          this.lowerLoading = false
          this.upperLoading = false
        }
      )
    },
    getCompanyInfo() {
      // 调用供应商详情接口，把单据对应的供应商存储到历史记录缓存中
      getAction('/xgh/company/queryById', {
        id: this.queryData.xghCompanyId,
      }).then((res) => {
        if (res.code === 200) {
          this.onSelectSupplier(res.result)
        }
      })
    },
    // 处理请求到的数据
    handleData(res) {
      console.log('handleData')
      let orderObj = res.saleStorehouseOrderPage
      let payObj = res.collectionPayPage || { xghCollectionPayInfoList: [] }
      //公用信息
      this.billId = orderObj.id
      this.orderStatus = orderObj.orderStatus
      this.logData.orderId = orderObj.id

      //单据信息
      this.queryData = {
        ...orderObj,
        orderDiscountPrice: formatMoney(orderObj.orderDiscountPrice),
        receivablePrice: formatMoney(orderObj.receivablePrice),
        owePrice: formatMoney(orderObj.owePrice),
        collectionPrice: formatMoney(orderObj.collectionPrice),
        allPrice: formatMoney(orderObj.allPrice),
        isSupplement: orderObj.isReplacementOrder == '1' ? false : true, //是否补单-0：是 1:不是
        expressStatus: orderObj.expressStatus == '1' ? false : true, //物流状态-0：开启 1:关闭
        expressPayStatus: orderObj.expressPayStatus == '1' ? true : false, //物流费付款状态1：已付款，2：未付
        orderRebate: orderObj.orderRebate + '',
      }
      this.taxRate = this.getTaxRate()
      this.attachments = (this.queryData.attachment || '').split(',').filter((item) => item)
      //商品明细
      const newTableList = orderObj.xghSaleStorehouseOrderInfoList
      newTableList.forEach((item) => {
        item.isGive = item.isGift == '0' ? true : false //赠品0:是赠品1：不是赠品

        item.number = formatFour(item.number)
        item.numberShow = formatNumber(item.number)
        item.deliverNum = formatNumber(item.deliverNum)
        item.salePrice = formatFour(item.salePrice)
        item.allPrice = formatFour(item.allPrice)
        item.discountUnitPrice = formatFour(item.discountUnitPrice)
        item.taxUnitPrice = formatFour(item.taxUnitPrice)
        item.taxPrice = formatFour(item.taxPrice)
        item.discountRate = Number(item.discountRate)
        item.salePriceShow = formatPrice(item.salePrice)
        item.discountUnitPriceShow = formatPrice(item.discountUnitPrice)
        item.taxUnitPriceShow = formatPrice(item.taxUnitPrice)
        item.taxPriceShow = formatMoney(item.taxPrice)
        item.goodsName = item.goodsName ? item.goodsName : item.goodsId_dictText
        item.compulsory = '0'
        item.unitList = item.goodsManyNorms
        //taxUnitPriceShow 

         item.allPriceShow = formatMoney(item.allPrice) //该方法都是后端返回的数据，不清楚为什么重新计算总价
        // item.allPriceShow = formatMoney(accMul(delcommafy(formatNumber(item.number)), delcommafy(formatPrice(item.taxUnitPrice))))

        // 特殊功能
        item.specialColorSize = (item.specialFunctionType || '').includes('1')
        item.showSpeial = true
        item.attributeOrderInfoRequest = getAttributeOrderInfoRequest(item.attributeGoodsResponse)
      })
      // 增加字段数据，避免不能更新页面
      this.TableConfig.tableData = JSON.parse(JSON.stringify(newTableList))
      for (let index = 0; index < this.TableConfig.tableData.length; index++) {
        const element = this.TableConfig.tableData[index];
        if (element.formulaId) {
          this.$refs.newTableRef.formulaChange(element.formulaId, element, index) 
        } 
      }

      // 支付信息
      this.paymentEcho = payObj
      let list = payObj.xghCollectionPayInfoList
      let names = []
      for (let index = 0; index < list.length; index++) {
        const element = list[index]
        if (element.price != 0) {
          //理论上都大于0
          names.push(element.bankName)
        }
      }
      this.queryData.bankName = names.join(';')
      this.printData = {
        ...this.queryData,
        ...getPrintCompanyInfo(this.gysOptions, this.queryData.xghCompanyId),
        printExclusive: this.TableConfig.tableData,
      }

      //物流信息
      this.xghExpressDetail = (res.xghExpressDetailVo && res.xghExpressDetailVo.xghExpressDetail) || {}
      this.collectionPayPage = (res.xghExpressDetailVo && res.xghExpressDetailVo.collectionPayPage) || {}
      let expressList = this.collectionPayPage.xghCollectionPayInfoList || []
      this.expressPaymentEcho = expressList
      this.expressPaymentEcho.forEach((item) => {
        item.receivablePrice = item.price
      })
      //物流代收id
      this.queryData.xghExpressDetailId = (res.expressCollectionPayPage && res.expressCollectionPayPage.id) || ''

      this.saveData = JSON.parse(
        JSON.stringify({
          ...this.queryData,
          ...this.TableConfig.tableData,
        })
      )
    },
    /**
     * 选择仓库数据
     */
    onChangeCk() {
      let result = false
      for (let index = 0; index < this.TableConfig.tableData.length; index++) {
        const element = this.TableConfig.tableData[index]
        if (element.goodsId) {
          result = true
          break
        }
      }
      if (result) {
        this.tipsData.tipsWords = '是否更新单据明细中的仓库？'
        this.tipsData.tipsMark = 'onChangeCk'
        this.$refs.reminderRef.dialogVisible = true
      } else if (this.TableConfig.tableData.length == 1 && !this.TableConfig.tableData[0].goodsId) {
        this.TableConfig.tableData[0].xghStorehouseId = this.queryData.xghOutStorehouseId
      }
    },

    // 打开新增仓库的弹框
    onShowWhAdd() {
      this.$refs.warehouseAddRef.dialogVisible = true
    },
    // 新增仓库数据
    async onAddWh(val) {
      val.isMain = val.isMain == true ? 1 : 0
      const res = await postAction('/xghStorehouse/xghStorehouse/add', val)
      if (res.code == 200) {
        this.$elMessage.success(res.message)
        this.getWarehouseData()
      } else {
        this.$elMessage.error(res.message)
      }
    },
    // 关闭新增仓库时清空
    onCloseAddWh() {
      this.newWhData = this.$options.data().newWhData
    },
    hongchongSure() {
      // 红冲
      this.updateOrder(20)
    },
    // 销售出库单审核
    updateOrder(state) {
      getAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/changeStatus', {
        id: this.billId,
        code: state,
        negativeInventory: this.isBaseVersion ? '1' : this.negativeInventory ? '1' : '0',
      })
        .then((res) => {
          if (res.code === 200) {
            this.$EventBus.$emit('update-data-state', {
              isOnSubmit: 2
            })
            this.orderStatus = state
            this.queryData.orderStatus_dictText = this.getOrderStatusText(state)
            this.$refs.simplePrompt.show({
              index: 0,
              text: this.getMessageByChangeOrderStatus(state),
            })
            if (state == 5) {
              this.afterExamine()
            }
          } else if (res.code == 48) {
            let config = sysConfig()
            let show = false
            let name = ''
            if (config.allow_negative_inventory) {
              // 允许负库存
              show = true
              name = `商品${res.message}库存不足, 是否继续审核?`
            } else {
              show = false
              name = `商品${res.message}库存不足, 并且不允许负库存, 无法进行审核!`
            }
            this.showNegativeInventoryDialog = true
            let item = {
              id: '',
              name: name,
              index: 2,
              show: show,
            }
            this.negativeInventoryData = item
          } else if (res.code == 49) {
            // 红冲 负库存 提醒
            let show = true
            let name = `商品${res.message}库存不足, 是否继续红冲?`
            this.showNegativeInventoryDialog = true
            let item = {
              id: '',
              name: name,
              index: 3,
              show: show,
            }
            this.negativeInventoryData = item
          } else {
            this.showTips(res.message)
          }
        })
        .finally(() => {
          this.examineLoading = false
        })
    },
    getOrderStatusText(os) {
      let object = {
        0: '待审核',
        5: '已审核',
        10: '已作废',
        15: '待审核',
        20: '已红冲',
        25: '已终止',
        30: '已完成',
      }
      return object[os + '']
    },
    getMessageByChangeOrderStatus(os) {
      let object = {
        5: '单据审核成功',
        10: '单据作废成功',
        15: '单据反审成功',
        20: '单据红冲成功',
        25: '单据终止成功',
        30: '单据已完成',
      }
      return object[os + '']
    },
    // 根据出货仓库选择商品里的仓库
    // force是否强制更新，true 用户选择不更新单据详情时 为空的强制赋值，false 选择更新单据 全部覆盖
    getXghStorehouseIdById(force) {
      this.TableConfig.tableData.forEach((item) => {
        if (force) {
          if (!item.xghStorehouseId) {
            item.xghStorehouseId = this.queryData.xghOutStorehouseId
          }
        } else {
          item.xghStorehouseId = this.queryData.xghOutStorehouseId
        }
      })
    },
    // 上一条
    onUpper() {
      if (this.orderStatus == 66 && this.getHaveChange()) {
        this.tipsData.tipsWords = '当前单据还未保存，</br>是否继续？'
        this.tipsData.tipsMark = 'onUpper'
        this.$refs.reminderRef.dialogVisible = true
      } else {
        this.orderFlag = 1 // 上一条
        this.switchoverBill(1)
      }
    },
    // 下一条
    onLower() {
      if (this.orderStatus == 66 && this.getHaveChange()) {
        this.tipsData.tipsWords = '当前单据还未保存，</br>是否继续？'
        this.tipsData.tipsMark = 'onLwer'
        this.$refs.reminderRef.dialogVisible = true
      } else {
        this.orderFlag = 2 // 下一页
        this.switchoverBill(2)
      }
    },
    switchoverBill(flag) {
      // if (this.orderFlag === 0) {
      //   this.orderFlag = flag
      // }
      if (flag === 1) {
        //flag 1 上一条
        //flag 2 下一条
        if (this.pageNo <= 1) {
          this.$elMessage.warning('已经是第一条了')
          return
        }
        this.pageNo -= 1
        this.upperLoading = true
        this.getOrderData(0)
      } else if (flag === 2) {
        console.log('页码数',this.pageNo);
          console.log('总页码数',this.pageTotal);
        if (this.pageNo >= this.pageTotal) {
          this.$elMessage.warning('已经是最后一条了')
          return
        }
       this.pageNo += 1
       this.lowerLoading = true
       this.getOrderData(1)
      }
    },

    // 打开新增经手人的弹框
    onShowStaffAdd() {
      this.$refs.staffAddRef.dialogVisible = true
    },
    // 获取新增经手人数据
    onAddStaff(val) {
      postAction('/dept/xghAccountBookDept/addAccountBookUser', val).then((res) => {
        if (res.code === 200) {
          this.$elMessage.success(res.message)
          this.$refs.staffAddRef.dialogVisible = false
          this.getStaffData()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 关闭新增员工时清空
    onCloseAddStaff() {},
    // 打开新增客户弹出框
    onShowSupplierAdd() {
      this.newData = {
        id: '',
        companyName: '',
        companyUserName: '',
        xghCompanyNatureId: '',
        xghCompanyNature: '',
        companyPhone: '',
        companyPinyinCode: '',
        companyLandline: '',
        xghCompanyTypeId: '', //单位类别
        xghCompanyType: '',
        business: '',
        provinceName: '', //省
        provinceCode: '',
        cityName: '', //市
        cityCode: '',
        countyName: '', //区县
        countyCode: '',
        address: '',
        setPrice: '',
        setDiscountPrice: '',
        companyInvoiceStatus: true,
        depositBank: '',
        bankName: '',
        bakCard: '',
        taxNumber: '',
        invoiceAddress: '',
        bankPhone: '',
        companyRAndPStatus: true,
        beginReceivable: 0,
        beginPayable: 0,
        totalReceivable: 0,
        totalPayable: 0,
        receivableQuota: '',
        payableQuota: '',
        receivableTime: '',
        payableTime: '',
        companyRemark: '',
      }
      this.$refs.supplierAddRef.dialogVisible = true
    },
    onShowLogisticsAdd() {
      this.$refs.dialogLogisticsAdd.add()
    },
    //新增物流公司
    onAddLogistics(val) {
      postAction('/xghExpress/xghExpress/add', val).then((res) => {
        if (res.code === 200) {
          this.$elMessage({
            message: '添加成功！',
            type: 'success',
          })
          this.getExpressList()
        }
      })
    },
    // 新增客户数据
    onAddSupplier(res) {
      this.getGysStorage()
    },
    // 关闭新增供应商弹框
    onCloseAddSupplier() {},
    // 打开选择客户弹出框
    onShowSupplier() {
      this.$refs.supplierRef.openDialog()
    },
    // 当前选择客户数据
    onSelectSupplier(val) {
      this.queryData.xghCompanyId = val.id
    },
    // 当前选择账户支付数据
    onSelectPayment(val) {
      let names = []
      let list = []
      let sum = 0
      val.forEach((item) => {
        if (Number(item.price) > 0) {
          let nIt = {
            companyId: this.queryData.xghCompanyId,
            companyType: this.paymentType == '2' ? 2 : 1, //单位类型1:快递收付 2;往来单位收付3：银行账户id
            isBegin: 1, //是否期初0：是期初 1：不是
            payType: 1, //收付类型1:收款2：付款
            price: item.price,
            xghAccountBookId: this.accountBookId,
            bankId: item.id,
            bankName: item.bankName,
          }
          sum = Number(sum) + Number(item.price)
          names.push(item.bankName)
          list.push(nIt)
        }
      })
      // 付款
      if (this.paymentType == '2') {
        this.queryData.bankName = names.join(';')
        this.paymentEcho.xghCollectionPayInfoList = list
        this.queryData.collectionPrice = sum
        // 本次欠款 = 单据金额 - 预收定金
        this.handlePriceChange()
      } else {
        // 物流费用
        this.queryData.expressPrice = sum
        list.forEach((item) => {
          item.receivablePrice = sum
          item.expressPrice = item.price
          item.expressType = '6'
        })
        this.expressPaymentEcho = list
        this.queryData.expressPayStatus = sum != 0
      }
    },
    // 历史记录数据去重并只展示三个数据方法
    selectDataHas(arr) {
      let map = new Map()
      for (const item of arr) {
        if (!map.has(item.id)) {
          map.set(item.id, item)
        }
      }
      let newArr = [...map.values()]
      return newArr.slice(0, 3)
    },
    // 打开操作日志弹框
    onShowLog() {
      this.$refs.operationLogRef.getData(this.logData)
      this.logTitle = '单据操作日志'
      this.$refs.operationLogRef.dialogVisible = true
    },
    // 搜索
    handleFilterMethod(value, label) {
      if (label == 'companyName') {
        this.gysOptions = this.filterMethod(this.gysOptions, value, label)
      } else if (label == 'storehouseName') {
        this.ckOptions = this.filterMethod(this.ckOptions, value, label)
      } else if (label == 'realname') {
        this.jsrOptions = this.filterMethod(this.jsrOptions, value, label)
      } else if (label == 'expressName') {
        this.wlgsOptions = this.filterMethod(this.wlgsOptions, value, label)
      }
    },
    // 判断是否有反审权限
    async checkReVerifyPermission() {
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      let accountId = accountBook && accountBook.id
      var res = await getAction('/sysConfig/systemConfig/checkReVerifyPermission', {
        xghAccountBookId: accountId,
      })
      if (res.success) {
        this.onUnToExamine()
      } else {
        this.$refs.deApprovalRef.dialogVisible = true
      }
    },
    onUnToExamine() {
      getAction('/xghSaleStorehouseOrder/xghSaleStorehouseOrder/changeStatus', {
        id: this.billId,
        code: 15,
      }).then((res) => {
        if (res.code === 200) {
          this.orderStatus = 0
          this.queryData.orderStatus = 0
          this.queryData.orderStatus_dictText = this.getOrderStatusText(0)
          this.saveData.orderStatus = 0
          this.saveData.orderStatus_dictText = this.getOrderStatusText(0)
          this.$refs.simplePrompt.show({
            index: 0,
            text: '单据反审成功',
          })
        } else if (res.code === 500) {
          this.showTips(res.message)
        }
      })
    },
    // // 获取收款码
    // getConfig() {
    //   getAction('/xghOrderRecord/xghOrderRecord/getConfig', {  }).then((res) => {
    //       if (res.success) {
    //         if (res.result.paymentQrCode) {
    //           this.paymentCode.push(res.result.paymentQrCode)
    //         }
    //       } else {
    //         this.$message.error(res.message)
    //       }
    //     }
    //   )
    // },
    // 生成收款码
    applyCode() {
      if(this.paymentApply){
          this.$refs.applyCode.show(1)
				}else{
					this.$message.warning('已提交申请，请耐心等待')
				}
    },
    // 获取申请状态
    getApplyState () {
      let params = {
        accountBookId: Vue.ls.get(ACCOUNT_BOOK).id,
      }
      console.log(params)
      getAction('/xghRequestForm/xghRequestForm/accountInfo',params).then((res) => {
        if (res.success) {
          let list = res.result
          if (list.length !== 0) {
            const hasType1 = list.some(item => item.requestType == 1);
            this.paymentApply = !hasType1;
            console.log('-----------------',this.paymentApply)
            // 如果有item.requestType == 1这一项，取出这一项的qrCode
            if (hasType1) {
              const type1Item = list.find(item => item.requestType == 1);
              console.log('type1Item:', type1Item);
              if (type1Item) {
                const qrCode = type1Item.qrCode;
                console.log('qrCode:', qrCode);
                if(qrCode){
                  this.paymentCode = [qrCode]; //商户固定收款码
                }
                // this.paymentCode = ['http://bpic.588ku.com//original_origin_min_pic/19/03/17/b5b47fecbc81417f72750024f8425654.jpg']
              }
            }
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.custom_more{
  right: 33px;
  // right: 21px;
}
.custom_select_head{
  display: flex; 
  align-items: center;
}
.el-select-dropdown {
  .el-scrollbar__view {
    max-height: 250px;
    overflow: auto;

    .add_select {
      &:last-of-type {
        margin-bottom: 40px;
      }
    }

    .last_li {
      position: absolute;
      bottom: 0px;
      width: 100%;
      height: 40px;
      background: #fff;
      line-height: 40px;
      font-size: 14px;
      color: #0089ff;
      cursor: pointer;
    }
  }
}

.basic_info {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
  box-sizing: border-box;
  padding: 0 10px 10px 10px;
  display: flex;
  flex-direction: column;
}

.info_operation_btn {
  width: 100%;
  // height: 50px;
  padding: 5px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-family: PingFang SC;
  font-size: 12px;

  ::v-deep .el-button {
    // width: 70px;
    height: 30px;
    text-align: center;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    border-radius: 0.093756rem;
    border: none;
    margin-right: 0.1rem;
    margin-left: 0;
    padding: 9px 0.2rem;
  }

  // .el-button--default {
  //   color: #666;
  // }

  ::v-deep .el-select {
    height: 30px;
    box-sizing: border-box;
    margin-right: 0.1rem;

    .el-input {
      height: 100%;

      .el-input__inner {
        width: 70px;
        height: 100%;
        border: none;
        font-size: 12px;
      }

      .el-input__suffix {
        height: 100%;
        display: flex;
        align-items: center;
      }

      .el-textarea {
        height: 100%;
        width: 30px;
      }
    }
  }

  ::v-deep .el-checkbox {
    display: flex;
    align-items: center;
    margin-left: 10px;

    .el-checkbox__input {
      height: 19px;
      display: flex;
      align-items: center;
    }

    .el-checkbox__label {
      font-size: 12px;
      padding-left: 5px;
      color: #666;
    }

    .is-checked {
      .el-checkbox__inner {
        background: #1a93fa;
        border-color: #1a93fa;
      }
    }
  }

  .arrow_btn {
    width: 30px;
    height: 30px;
    background: #ffffff;
    padding: 0;
    margin-right: 0;
  }

  p {
    font-size: 12px;
    color: #666;
    margin-right: 0.25rem;
  }

  .search_order {
    display: flex;
    align-items: center;
    margin-left: 10px;

    p {
      margin-right: 0;
    }
  }

  .btn_left {
    height: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    // flex-wrap: wrap;
    // line-height: 30px;
  }

  .btn_right {
    height: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-shrink: 0;
  }
}

.info_content_div {
  width: 100%;
  height: calc(100% - 50px);
  background: #fff;
  box-sizing: border-box;
  padding: 0 10px;
  display: flex;

  .div_table {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .div_screen {
      width: 100%;
      // heig ht: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      ::v-deep .el-select {
        height: 30px;
        box-sizing: border-box;
        margin-right: 10px;

        .el-input {
          height: 100%;

          .el-input__inner {
            height: 100%;
            font-size: 12px;
          }

          .el-input__suffix {
            height: 100%;
            display: flex;
            align-items: center;
          }

          .el-textarea {
            height: 100%;
            width: 30px;
          }
        }
      }

      ::v-deep .el-date-editor {
        width: 120px;
        height: 30px;

        .el-input__inner {
          width: 100%;
          height: 30px;
          padding: 0 0.187512rem;
          font-size: 12px;
          color: #666;
        }

        .el-input__prefix {
          left: unset;
          right: 5px !important;

          .el-input__icon {
            line-height: 30px;
            font-size: 16px;
          }
        }

        .el-input__suffix {
          display: none;
        }
      }

      .screen_right {
        width: 30px;
        height: 30px;
        box-sizing: border-box;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;

        .set_up {
          line-height: 20px;
          font-size: 20px;
          color: rgb(153, 153, 153);
        }
      }
    }
    
    .table_content {
      flex: 1;
      margin-top: 10px;
      box-sizing: border-box;
      overflow: auto;

      > div {
        width: 100%;
        height: 100%;
        border: 1px solid #e3e3e3;
      }
    }

    .table_calculation {
      width: 100%;
      height: 170px;
      box-sizing: border-box;
      padding: 10px 0;
      display: flex;
      justify-content: space-between;
      overflow: hidden;
      overflow-x: scroll;

      > div {
        display: flex;

        .calculation_div {
          .table_item {
            height: 30px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;

            ::v-deep .el-button {
              width: 80px;
              height: 30px;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 12px;
              color: #666;
              background: #fff;
            }

            .el-button--primary {
              color: #1b94fb;
              border-color: #1b94fb;
            }

            > p,
            span {
              margin: 0;
              font-size: 12px;
              color: #666;
            }

            > p {
              width: 50px;
              text-align: justify;
              text-justify: distribute-all-lines;
              /*ie6-8*/
              text-align-last: justify;
              /* ie9*/
              -moz-text-align-last: justify;
              /*ff*/
              -webkit-text-align-last: justify;
              /*chrome 20+*/
            }

            > ::v-deep .el-input {
              width: 312px;
              height: 30px;

              .el-input__inner {
                height: 100%;
                padding: 0 0.150009rem;
                font-size: 12px;
                color: #666;
              }
            }

            ::v-deep .el-select {
              width: 1rem;
              height: 30px;
              box-sizing: border-box;
              border-radius: 4px;

              .el-input {
                .el-input__inner {
                  // height: 0.562535rem;
                  height: 30px;
                  border-color: #e3e3e3;
                  // font-size: 0.225014rem;
                  font-size: 12px;
                  padding-left: 0.150009rem;
                }

                .el-input__suffix {
                  // height: 0.562535rem;
                  height: 30px;
                  display: flex;
                  align-items: center;
                }
              }
            }

            .createQR {
              border: #1b94fb 1px solid;
              color: #1b94fb;
            }

            .payDate_input {
              // height: 0.562535rem;
              height: 30px;
              position: relative;
              display: flex;
              align-items: center;

              ::v-deep .el-input {
                width: 100%;
                // height: 0.562535rem;
                height: 30px;

                .el-input__inner {
                  height: 100%;
                  padding: 0 0.468779rem 0 0.187512rem;
                  // font-size: 0.225014rem;
                  font-size: 12px;
                  color: #666;
                  text-align: left;
                  text-align-last: left;
                }
              }

              i {
                position: absolute;
                right: 0.12rem;
                // margin-right: 0.187512rem;
                color: #bfbfbf;
                font-size: 20px;
                cursor: pointer;
              }
            }

            .span_style {
              font-size: 24px;
              font-family: PingFang SC;
              font-weight: 600;
              color: #ff6c00;
            }

            &:last-child {
              margin-bottom: 0;
            }
          }

          .switch_p {
            width: max-content;
            margin-right: 10px;
          }

          .question_mark {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            cursor: pointer;
          }

          .tips_div {
            // width: 220px;
            height: 30px;
            background: #fcf2a8;
            border: 1px solid #e8b28a;
            box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.16);
            opacity: 1;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 0.150009rem;

            p {
              // font-size: 0.225014rem;
              font-size: 12px;
              color: #666666;
              margin: 0;
              font-family: PingFang SC;
              font-weight: 400;
            }

            .exclamatory_mark {
              font-size: 0.262516rem;
              margin-right: 0.150009rem;
            }

            i {
              font-size: 12px;
              color: #666;
            }
          }
        }
      }
    }
  }
}

.bill_mask_view_script {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 40px;
  z-index: 10;
}
.act_view {
  width: 220px;
  padding-left: 20px;
}
.uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  width: 52px;
  height: 52px;
  margin: 0 10px 6px 0;
}
.attachment_view {
  border: 1px dashed white;
  width: 52px;
  height: 52px;
  background-color: #f6f6f6;
  line-height: 40px;
  text-align: center;
  border-radius: 3px;
  margin: 0 10px 6px 0;
}
.attachment_mask {
  z-index: 2;
  position: absolute;
  right: 0;
  top: 0;
  width: 12px;
  height: 12px;
  display: flex;
  align-items: center;
}
.attachment_mask_pre {
  z-index: 1;
  position: absolute;
  display: flex;
  align-items: center;
  pointer-events: none;
  right: 0;
  top: 0;
  left: 0;
  bottom: 0;
  backdrop-filter: blur(1px);
  img{
    position: absolute;
    width: 14px;
    height: 14px;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
  }
}
.default-button {
  padding: 5px 10px;
  border: #0089ff 1px solid;
  border-radius: 5px;
  color: #0089ff;
  height: max-content;
  margin: 0 10px;
  flex-shrink: 0;
  cursor: pointer;
}
.default {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: auto;
  height: auto;
  
  .default-span {
    line-height: 28px !important;
    font-weight: 500 !important;
    font-size: 12px !important;
    color: #0089FF !important;
  }
}
</style>
